repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/modules/postgres.py
is_installed_extension
python
def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext)
Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1514-L1539
[ "def get_installed_extension(name,\n user=None,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None):\n '''\n Get info about an installed postgresql extension\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.get_installed_extension plpgsql\n\n '''\n return installed_extensions(user=user,\n host=host,\n port=port,\n maintenance_db=maintenance_db,\n password=password,\n runas=runas).get(name, None)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
create_metadata
python
def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret
Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1542-L1586
[ "def get_installed_extension(name,\n user=None,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None):\n '''\n Get info about an installed postgresql extension\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.get_installed_extension plpgsql\n\n '''\n return installed_extensions(user=user,\n host=host,\n port=port,\n maintenance_db=maintenance_db,\n password=password,\n runas=runas).get(name, None)\n", "def _pg_is_older_ext_ver(a, b):\n '''\n Compare versions of extensions using salt.utils.versions.LooseVersion.\n\n Returns ``True`` if version a is lesser than b.\n '''\n return _LooseVersion(a) < _LooseVersion(b)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
drop_extension
python
def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret
Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1589-L1645
[ "def _psql_prepare_and_run(cmd,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None,\n user=None):\n rcmd = _psql_cmd(\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n *cmd)\n cmdret = _run_psql(\n rcmd, runas=runas, password=password, host=host, port=port, user=user)\n return cmdret\n", "def is_installed_extension(name,\n user=None,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None):\n '''\n Test if a specific extension is installed\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.is_installed_extension\n\n '''\n installed_ext = get_installed_extension(\n name,\n user=user,\n host=host,\n port=port,\n maintenance_db=maintenance_db,\n password=password,\n runas=runas)\n return bool(installed_ext)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
create_extension
python
def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret
Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1648-L1735
[ "def _psql_prepare_and_run(cmd,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None,\n user=None):\n rcmd = _psql_cmd(\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n *cmd)\n cmdret = _run_psql(\n rcmd, runas=runas, password=password, host=host, port=port, user=user)\n return cmdret\n", "def is_available_extension(name,\n user=None,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None):\n '''\n Test if a specific extension is available\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.is_available_extension\n\n '''\n exts = available_extensions(user=user,\n host=host,\n port=port,\n maintenance_db=maintenance_db,\n password=password,\n runas=runas)\n if name.lower() in [\n a.lower()\n for a in exts\n ]:\n return True\n return False\n", "def create_metadata(name,\n ext_version=None,\n schema=None,\n user=None,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None):\n '''\n Get lifecycle information about an extension\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.create_metadata adminpack\n\n '''\n installed_ext = get_installed_extension(\n name,\n user=user,\n host=host,\n port=port,\n maintenance_db=maintenance_db,\n password=password,\n runas=runas)\n ret = [_EXTENSION_NOT_INSTALLED]\n if installed_ext:\n ret = [_EXTENSION_INSTALLED]\n if (\n ext_version is not None\n and _pg_is_older_ext_ver(\n installed_ext.get('extversion', ext_version),\n ext_version\n )\n ):\n ret.append(_EXTENSION_TO_UPGRADE)\n if (\n schema is not None\n and installed_ext.get('extrelocatable', 'f') == 't'\n and installed_ext.get('schema_name', schema) != schema\n ):\n ret.append(_EXTENSION_TO_MOVE)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
user_remove
python
def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas)
Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1738-L1760
[ "def _role_remove(name, user=None, host=None, port=None, maintenance_db=None,\n password=None, runas=None):\n '''\n Removes a role from the Postgres Server\n '''\n\n # check if user exists\n if not user_exists(name, user, host, port, maintenance_db,\n password=password, runas=runas):\n log.info('User \\'%s\\' does not exist', name)\n return False\n\n # user exists, proceed\n sub_cmd = 'DROP ROLE \"{0}\"'.format(name)\n _psql_prepare_and_run(\n ['-c', sub_cmd],\n runas=runas, host=host, user=user, port=port,\n maintenance_db=maintenance_db, password=password)\n\n if not user_exists(name, user, host, port, maintenance_db,\n password=password, runas=runas):\n return True\n else:\n log.info('Failed to delete user \\'%s\\'.', name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
group_create
python
def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas)
Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1765-L1809
[ "def _role_create(name,\n user=None,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n createdb=None,\n createroles=None,\n encrypted=None,\n superuser=None,\n login=None,\n connlimit=None,\n inherit=None,\n replication=None,\n rolepassword=None,\n valid_until=None,\n typ_='role',\n groups=None,\n runas=None):\n '''\n Creates a Postgres role. Users and Groups are both roles in postgres.\n However, users can login, groups cannot.\n '''\n\n # check if role exists\n if user_exists(name, user, host, port, maintenance_db,\n password=password, runas=runas):\n log.info('%s \\'%s\\' already exists', typ_.capitalize(), name)\n return False\n\n sub_cmd = 'CREATE ROLE \"{0}\" WITH'.format(name)\n sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args(\n name,\n typ_=typ_,\n encrypted=encrypted,\n login=login,\n connlimit=connlimit,\n inherit=inherit,\n createdb=createdb,\n createroles=createroles,\n superuser=superuser,\n groups=groups,\n replication=replication,\n rolepassword=rolepassword,\n valid_until=valid_until\n ))\n ret = _psql_prepare_and_run(['-c', sub_cmd],\n runas=runas, host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n password=password)\n\n return ret['retcode'] == 0\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
group_remove
python
def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas)
Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1858-L1880
[ "def _role_remove(name, user=None, host=None, port=None, maintenance_db=None,\n password=None, runas=None):\n '''\n Removes a role from the Postgres Server\n '''\n\n # check if user exists\n if not user_exists(name, user, host, port, maintenance_db,\n password=password, runas=runas):\n log.info('User \\'%s\\' does not exist', name)\n return False\n\n # user exists, proceed\n sub_cmd = 'DROP ROLE \"{0}\"'.format(name)\n _psql_prepare_and_run(\n ['-c', sub_cmd],\n runas=runas, host=host, user=user, port=port,\n maintenance_db=maintenance_db, password=password)\n\n if not user_exists(name, user, host, port, maintenance_db,\n password=password, runas=runas):\n return True\n else:\n log.info('Failed to delete user \\'%s\\'.', name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
owner_to
python
def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret
Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1883-L1955
[ "def _psql_prepare_and_run(cmd,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None,\n user=None):\n rcmd = _psql_cmd(\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n *cmd)\n cmdret = _run_psql(\n rcmd, runas=runas, password=password, host=host, port=port, user=user)\n return cmdret\n", "def psql_query(query, user=None, host=None, port=None, maintenance_db=None,\n password=None, runas=None, write=False):\n '''\n Run an SQL-Query and return the results as a list. This command\n only supports SELECT statements. This limitation can be worked around\n with a query like this:\n\n WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE\n rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated;\n\n query\n The query string.\n\n user\n Database username, if different from config or default.\n\n host\n Database host, if different from config or default.\n\n port\n Database port, if different from the config or default.\n\n maintenance_db\n The database to run the query against.\n\n password\n User password, if different from the config or default.\n\n runas\n User to run the command as.\n\n write\n Mark query as READ WRITE transaction.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.psql_query 'select * from pg_stat_activity'\n '''\n ret = []\n\n csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format(\n query.strip().rstrip(';'))\n\n # Mark transaction as R/W to achieve write will be allowed\n # Commit is necessary due to transaction\n if write:\n csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query)\n\n # always use the same datestyle settings to allow parsing dates\n # regardless what server settings are configured\n cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY',\n '-c', csv_query],\n runas=runas,\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n password=password)\n if cmdret['retcode'] > 0:\n return ret\n\n csv_file = StringIO(cmdret['stdout'])\n header = {}\n for row in csv.reader(csv_file,\n delimiter=salt.utils.stringutils.to_str(','),\n quotechar=salt.utils.stringutils.to_str('\"')):\n if not row:\n continue\n if not header:\n header = row\n continue\n ret.append(dict(zip(header, row)))\n\n # Remove 'COMMIT' message if query is inside R/W transction\n if write:\n ret = ret[0:-1]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
schema_create
python
def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0
Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1960-L1993
[ "def _psql_prepare_and_run(cmd,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None,\n user=None):\n rcmd = _psql_cmd(\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n *cmd)\n cmdret = _run_psql(\n rcmd, runas=runas, password=password, host=host, port=port, user=user)\n return cmdret\n", "def schema_exists(dbname, name, user=None,\n db_user=None, db_password=None,\n db_host=None, db_port=None):\n '''\n Checks if a schema exists on the Postgres server.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.schema_exists dbname schemaname\n\n dbname\n Database name we query on\n\n name\n Schema name we look for\n\n user\n The system user the operation should be performed on behalf of\n\n db_user\n database username if different from config or default\n\n db_password\n user password if any password for a specified user\n\n db_host\n Database host if different from config or default\n\n db_port\n Database port if different from config or default\n\n '''\n return bool(\n schema_get(dbname, name, user=user,\n db_user=db_user,\n db_host=db_host,\n db_port=db_port,\n db_password=db_password))\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
schema_remove
python
def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False
Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1996-L2053
[ "def _psql_prepare_and_run(cmd,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None,\n user=None):\n rcmd = _psql_cmd(\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n *cmd)\n cmdret = _run_psql(\n rcmd, runas=runas, password=password, host=host, port=port, user=user)\n return cmdret\n", "def schema_exists(dbname, name, user=None,\n db_user=None, db_password=None,\n db_host=None, db_port=None):\n '''\n Checks if a schema exists on the Postgres server.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.schema_exists dbname schemaname\n\n dbname\n Database name we query on\n\n name\n Schema name we look for\n\n user\n The system user the operation should be performed on behalf of\n\n db_user\n database username if different from config or default\n\n db_password\n user password if any password for a specified user\n\n db_host\n Database host if different from config or default\n\n db_port\n Database port if different from config or default\n\n '''\n return bool(\n schema_get(dbname, name, user=user,\n db_user=db_user,\n db_host=db_host,\n db_port=db_port,\n db_password=db_password))\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
schema_exists
python
def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password))
Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2056-L2095
[ "def schema_get(dbname, name, user=None,\n db_user=None, db_password=None,\n db_host=None, db_port=None):\n '''\n Return a dict with information about schemas in a database.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.schema_get dbname name\n\n dbname\n Database name we query on\n\n name\n Schema name we look for\n\n user\n The system user the operation should be performed on behalf of\n\n db_user\n database username if different from config or default\n\n db_password\n user password if any password for a specified user\n\n db_host\n Database host if different from config or default\n\n db_port\n Database port if different from config or default\n '''\n all_schemas = schema_list(dbname, user=user,\n db_user=db_user,\n db_host=db_host,\n db_port=db_port,\n db_password=db_password)\n try:\n return all_schemas.get(name, None)\n except AttributeError:\n log.error('Could not retrieve Postgres schema. Is Postgres running?')\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
schema_get
python
def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False
Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2098-L2140
[ "def schema_list(dbname, user=None,\n db_user=None, db_password=None,\n db_host=None, db_port=None):\n '''\n Return a dict with information about schemas in a Postgres database.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.schema_list dbname\n\n dbname\n Database name we query on\n\n user\n The system user the operation should be performed on behalf of\n\n db_user\n database username if different from config or default\n\n db_password\n user password if any password for a specified user\n\n db_host\n Database host if different from config or default\n\n db_port\n Database port if different from config or default\n '''\n\n ret = {}\n\n query = (''.join([\n 'SELECT '\n 'pg_namespace.nspname as \"name\",'\n 'pg_namespace.nspacl as \"acl\", '\n 'pg_roles.rolname as \"owner\" '\n 'FROM pg_namespace '\n 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner '\n ]))\n\n rows = psql_query(query, runas=user,\n host=db_host,\n user=db_user,\n port=db_port,\n maintenance_db=dbname,\n password=db_password)\n\n for row in rows:\n retrow = {}\n for key in ('owner', 'acl'):\n retrow[key] = row[key]\n ret[row['name']] = retrow\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
schema_list
python
def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret
Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2143-L2198
[ "def psql_query(query, user=None, host=None, port=None, maintenance_db=None,\n password=None, runas=None, write=False):\n '''\n Run an SQL-Query and return the results as a list. This command\n only supports SELECT statements. This limitation can be worked around\n with a query like this:\n\n WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE\n rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated;\n\n query\n The query string.\n\n user\n Database username, if different from config or default.\n\n host\n Database host, if different from config or default.\n\n port\n Database port, if different from the config or default.\n\n maintenance_db\n The database to run the query against.\n\n password\n User password, if different from the config or default.\n\n runas\n User to run the command as.\n\n write\n Mark query as READ WRITE transaction.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.psql_query 'select * from pg_stat_activity'\n '''\n ret = []\n\n csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format(\n query.strip().rstrip(';'))\n\n # Mark transaction as R/W to achieve write will be allowed\n # Commit is necessary due to transaction\n if write:\n csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query)\n\n # always use the same datestyle settings to allow parsing dates\n # regardless what server settings are configured\n cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY',\n '-c', csv_query],\n runas=runas,\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n password=password)\n if cmdret['retcode'] > 0:\n return ret\n\n csv_file = StringIO(cmdret['stdout'])\n header = {}\n for row in csv.reader(csv_file,\n delimiter=salt.utils.stringutils.to_str(','),\n quotechar=salt.utils.stringutils.to_str('\"')):\n if not row:\n continue\n if not header:\n header = row\n continue\n ret.append(dict(zip(header, row)))\n\n # Remove 'COMMIT' message if query is inside R/W transction\n if write:\n ret = ret[0:-1]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
language_list
python
def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret
.. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2201-L2253
[ "def psql_query(query, user=None, host=None, port=None, maintenance_db=None,\n password=None, runas=None, write=False):\n '''\n Run an SQL-Query and return the results as a list. This command\n only supports SELECT statements. This limitation can be worked around\n with a query like this:\n\n WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE\n rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated;\n\n query\n The query string.\n\n user\n Database username, if different from config or default.\n\n host\n Database host, if different from config or default.\n\n port\n Database port, if different from the config or default.\n\n maintenance_db\n The database to run the query against.\n\n password\n User password, if different from the config or default.\n\n runas\n User to run the command as.\n\n write\n Mark query as READ WRITE transaction.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.psql_query 'select * from pg_stat_activity'\n '''\n ret = []\n\n csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format(\n query.strip().rstrip(';'))\n\n # Mark transaction as R/W to achieve write will be allowed\n # Commit is necessary due to transaction\n if write:\n csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query)\n\n # always use the same datestyle settings to allow parsing dates\n # regardless what server settings are configured\n cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY',\n '-c', csv_query],\n runas=runas,\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n password=password)\n if cmdret['retcode'] > 0:\n return ret\n\n csv_file = StringIO(cmdret['stdout'])\n header = {}\n for row in csv.reader(csv_file,\n delimiter=salt.utils.stringutils.to_str(','),\n quotechar=salt.utils.stringutils.to_str('\"')):\n if not row:\n continue\n if not header:\n header = row\n continue\n ret.append(dict(zip(header, row)))\n\n # Remove 'COMMIT' message if query is inside R/W transction\n if write:\n ret = ret[0:-1]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
language_exists
python
def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages
.. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2256-L2303
[ "def language_list(\n maintenance_db,\n user=None,\n host=None,\n port=None,\n password=None,\n runas=None):\n '''\n .. versionadded:: 2016.3.0\n\n Return a list of languages in a database.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.language_list dbname\n\n maintenance_db\n The database to check\n\n user\n database username if different from config or default\n\n password\n user password if any password for a specified user\n\n host\n Database host if different from config or default\n\n port\n Database port if different from config or default\n\n runas\n System user all operations should be performed on behalf of\n '''\n\n ret = {}\n query = 'SELECT lanname AS \"Name\" FROM pg_language'\n\n rows = psql_query(\n query,\n runas=runas,\n host=host,\n user=user,\n port=port,\n maintenance_db=maintenance_db,\n password=password)\n\n for row in rows:\n ret[row['Name']] = row['Name']\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
language_create
python
def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0
.. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2306-L2360
[ "def _psql_prepare_and_run(cmd,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None,\n user=None):\n rcmd = _psql_cmd(\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n *cmd)\n cmdret = _run_psql(\n rcmd, runas=runas, password=password, host=host, port=port, user=user)\n return cmdret\n", "def language_exists(\n name,\n maintenance_db,\n user=None,\n host=None,\n port=None,\n password=None,\n runas=None):\n '''\n .. versionadded:: 2016.3.0\n\n Checks if language exists in a database.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.language_exists plpgsql dbname\n\n name\n Language to check for\n\n maintenance_db\n The database to check in\n\n user\n database username if different from config or default\n\n password\n user password if any password for a specified user\n\n host\n Database host if different from config or default\n\n port\n Database port if different from config or default\n\n runas\n System user all operations should be performed on behalf of\n\n '''\n\n languages = language_list(\n maintenance_db, user=user, host=host,\n port=port, password=password,\n runas=runas)\n\n return name in languages\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
_make_default_privileges_list_query
python
def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query
Generate the SQL required for specific object type
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2420-L2480
null
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
_make_privileges_list_query
python
def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query
Generate the SQL required for specific object type
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2483-L2560
null
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
_get_object_owner
python
def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret
Return the owner of a postgres object
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2563-L2650
[ "def psql_query(query, user=None, host=None, port=None, maintenance_db=None,\n password=None, runas=None, write=False):\n '''\n Run an SQL-Query and return the results as a list. This command\n only supports SELECT statements. This limitation can be worked around\n with a query like this:\n\n WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE\n rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated;\n\n query\n The query string.\n\n user\n Database username, if different from config or default.\n\n host\n Database host, if different from config or default.\n\n port\n Database port, if different from the config or default.\n\n maintenance_db\n The database to run the query against.\n\n password\n User password, if different from the config or default.\n\n runas\n User to run the command as.\n\n write\n Mark query as READ WRITE transaction.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.psql_query 'select * from pg_stat_activity'\n '''\n ret = []\n\n csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format(\n query.strip().rstrip(';'))\n\n # Mark transaction as R/W to achieve write will be allowed\n # Commit is necessary due to transaction\n if write:\n csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query)\n\n # always use the same datestyle settings to allow parsing dates\n # regardless what server settings are configured\n cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY',\n '-c', csv_query],\n runas=runas,\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n password=password)\n if cmdret['retcode'] > 0:\n return ret\n\n csv_file = StringIO(cmdret['stdout'])\n header = {}\n for row in csv.reader(csv_file,\n delimiter=salt.utils.stringutils.to_str(','),\n quotechar=salt.utils.stringutils.to_str('\"')):\n if not row:\n continue\n if not header:\n header = row\n continue\n ret.append(dict(zip(header, row)))\n\n # Remove 'COMMIT' message if query is inside R/W transction\n if write:\n ret = ret[0:-1]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
_validate_default_privileges
python
def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group')
Validate the supplied privileges
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2653-L2674
null
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
_mod_defpriv_opts
python
def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs
Format options
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2677-L2685
null
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
_process_defpriv_part
python
def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp
Process part
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2688-L2704
null
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
_validate_privileges
python
def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group')
Validate the supplied privileges
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2707-L2728
null
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
_mod_priv_opts
python
def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs
Format options
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2731-L2739
null
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
_process_priv_part
python
def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp
Process part
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2742-L2758
null
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
default_privileges_list
python
def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret
.. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2761-L2854
[ "def psql_query(query, user=None, host=None, port=None, maintenance_db=None,\n password=None, runas=None, write=False):\n '''\n Run an SQL-Query and return the results as a list. This command\n only supports SELECT statements. This limitation can be worked around\n with a query like this:\n\n WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE\n rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated;\n\n query\n The query string.\n\n user\n Database username, if different from config or default.\n\n host\n Database host, if different from config or default.\n\n port\n Database port, if different from the config or default.\n\n maintenance_db\n The database to run the query against.\n\n password\n User password, if different from the config or default.\n\n runas\n User to run the command as.\n\n write\n Mark query as READ WRITE transaction.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.psql_query 'select * from pg_stat_activity'\n '''\n ret = []\n\n csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format(\n query.strip().rstrip(';'))\n\n # Mark transaction as R/W to achieve write will be allowed\n # Commit is necessary due to transaction\n if write:\n csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query)\n\n # always use the same datestyle settings to allow parsing dates\n # regardless what server settings are configured\n cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY',\n '-c', csv_query],\n runas=runas,\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n password=password)\n if cmdret['retcode'] > 0:\n return ret\n\n csv_file = StringIO(cmdret['stdout'])\n header = {}\n for row in csv.reader(csv_file,\n delimiter=salt.utils.stringutils.to_str(','),\n quotechar=salt.utils.stringutils.to_str('\"')):\n if not row:\n continue\n if not header:\n header = row\n continue\n ret.append(dict(zip(header, row)))\n\n # Remove 'COMMIT' message if query is inside R/W transction\n if write:\n ret = ret[0:-1]\n\n return ret\n", "def _make_default_privileges_list_query(name, object_type, prepend):\n '''\n Generate the SQL required for specific object type\n '''\n if object_type == 'table':\n query = (' '.join([\n 'SELECT defacl.defaclacl AS name',\n 'FROM pg_default_acl defacl',\n 'JOIN pg_authid aid',\n 'ON defacl.defaclrole = aid.oid ',\n 'JOIN pg_namespace nsp ',\n 'ON nsp.oid = defacl.defaclnamespace',\n \"WHERE nsp.nspname = '{0}'\",\n \"AND defaclobjtype ='r'\",\n 'ORDER BY nspname',\n ])).format(prepend)\n elif object_type == 'sequence':\n query = (' '.join([\n 'SELECT defacl.defaclacl AS name',\n 'FROM pg_default_acl defacl',\n 'JOIN pg_authid aid',\n 'ON defacl.defaclrole = aid.oid ',\n 'JOIN pg_namespace nsp ',\n 'ON nsp.oid = defacl.defaclnamespace',\n \"WHERE nsp.nspname = '{0}'\",\n \"AND defaclobjtype ='S'\",\n 'ORDER BY nspname',\n ])).format(prepend, name)\n elif object_type == 'schema':\n query = (' '.join([\n 'SELECT nspacl AS name',\n 'FROM pg_catalog.pg_namespace',\n \"WHERE nspname = '{0}'\",\n 'ORDER BY nspname',\n ])).format(name)\n elif object_type == 'function':\n query = (' '.join([\n 'SELECT defacl.defaclacl AS name',\n 'FROM pg_default_acl defacl',\n 'JOIN pg_authid aid',\n 'ON defacl.defaclrole = aid.oid ',\n 'JOIN pg_namespace nsp ',\n 'ON nsp.oid = defacl.defaclnamespace',\n \"WHERE nsp.nspname = '{0}'\",\n \"AND defaclobjtype ='f'\",\n 'ORDER BY nspname',\n ])).format(prepend, name)\n elif object_type == 'group':\n query = (' '.join([\n 'SELECT rolname, admin_option',\n 'FROM pg_catalog.pg_auth_members m',\n 'JOIN pg_catalog.pg_roles r',\n 'ON m.member=r.oid',\n 'WHERE m.roleid IN',\n '(SELECT oid',\n 'FROM pg_catalog.pg_roles',\n \"WHERE rolname='{0}')\",\n 'ORDER BY rolname',\n ])).format(name)\n\n return query\n", "def _process_defpriv_part(defperms):\n '''\n Process part\n '''\n _tmp = {}\n previous = None\n for defperm in defperms:\n if previous is None:\n _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False\n previous = _DEFAULT_PRIVILEGES_MAP[defperm]\n else:\n if defperm == '*':\n _tmp[previous] = True\n else:\n _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False\n previous = _DEFAULT_PRIVILEGES_MAP[defperm]\n return _tmp\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
privileges_list
python
def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret
.. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2857-L2953
[ "def psql_query(query, user=None, host=None, port=None, maintenance_db=None,\n password=None, runas=None, write=False):\n '''\n Run an SQL-Query and return the results as a list. This command\n only supports SELECT statements. This limitation can be worked around\n with a query like this:\n\n WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE\n rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated;\n\n query\n The query string.\n\n user\n Database username, if different from config or default.\n\n host\n Database host, if different from config or default.\n\n port\n Database port, if different from the config or default.\n\n maintenance_db\n The database to run the query against.\n\n password\n User password, if different from the config or default.\n\n runas\n User to run the command as.\n\n write\n Mark query as READ WRITE transaction.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.psql_query 'select * from pg_stat_activity'\n '''\n ret = []\n\n csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format(\n query.strip().rstrip(';'))\n\n # Mark transaction as R/W to achieve write will be allowed\n # Commit is necessary due to transaction\n if write:\n csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query)\n\n # always use the same datestyle settings to allow parsing dates\n # regardless what server settings are configured\n cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY',\n '-c', csv_query],\n runas=runas,\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n password=password)\n if cmdret['retcode'] > 0:\n return ret\n\n csv_file = StringIO(cmdret['stdout'])\n header = {}\n for row in csv.reader(csv_file,\n delimiter=salt.utils.stringutils.to_str(','),\n quotechar=salt.utils.stringutils.to_str('\"')):\n if not row:\n continue\n if not header:\n header = row\n continue\n ret.append(dict(zip(header, row)))\n\n # Remove 'COMMIT' message if query is inside R/W transction\n if write:\n ret = ret[0:-1]\n\n return ret\n", "def _make_privileges_list_query(name, object_type, prepend):\n '''\n Generate the SQL required for specific object type\n '''\n if object_type == 'table':\n query = (' '.join([\n 'SELECT relacl AS name',\n 'FROM pg_catalog.pg_class c',\n 'JOIN pg_catalog.pg_namespace n',\n 'ON n.oid = c.relnamespace',\n \"WHERE nspname = '{0}'\",\n \"AND relname = '{1}'\",\n \"AND relkind = 'r'\",\n 'ORDER BY relname',\n ])).format(prepend, name)\n elif object_type == 'sequence':\n query = (' '.join([\n 'SELECT relacl AS name',\n 'FROM pg_catalog.pg_class c',\n 'JOIN pg_catalog.pg_namespace n',\n 'ON n.oid = c.relnamespace',\n \"WHERE nspname = '{0}'\",\n \"AND relname = '{1}'\",\n \"AND relkind = 'S'\",\n 'ORDER BY relname',\n ])).format(prepend, name)\n elif object_type == 'schema':\n query = (' '.join([\n 'SELECT nspacl AS name',\n 'FROM pg_catalog.pg_namespace',\n \"WHERE nspname = '{0}'\",\n 'ORDER BY nspname',\n ])).format(name)\n elif object_type == 'function':\n query = (' '.join([\n 'SELECT proacl AS name',\n 'FROM pg_catalog.pg_proc p',\n 'JOIN pg_catalog.pg_namespace n',\n 'ON n.oid = p.pronamespace',\n \"WHERE nspname = '{0}'\",\n \"AND p.oid::regprocedure::text = '{1}'\",\n 'ORDER BY proname, proargtypes',\n ])).format(prepend, name)\n elif object_type == 'tablespace':\n query = (' '.join([\n 'SELECT spcacl AS name',\n 'FROM pg_catalog.pg_tablespace',\n \"WHERE spcname = '{0}'\",\n 'ORDER BY spcname',\n ])).format(name)\n elif object_type == 'language':\n query = (' '.join([\n 'SELECT lanacl AS name',\n 'FROM pg_catalog.pg_language',\n \"WHERE lanname = '{0}'\",\n 'ORDER BY lanname',\n ])).format(name)\n elif object_type == 'database':\n query = (' '.join([\n 'SELECT datacl AS name',\n 'FROM pg_catalog.pg_database',\n \"WHERE datname = '{0}'\",\n 'ORDER BY datname',\n ])).format(name)\n elif object_type == 'group':\n query = (' '.join([\n 'SELECT rolname, admin_option',\n 'FROM pg_catalog.pg_auth_members m',\n 'JOIN pg_catalog.pg_roles r',\n 'ON m.member=r.oid',\n 'WHERE m.roleid IN',\n '(SELECT oid',\n 'FROM pg_catalog.pg_roles',\n \"WHERE rolname='{0}')\",\n 'ORDER BY rolname',\n ])).format(name)\n\n return query\n", "def _process_priv_part(perms):\n '''\n Process part\n '''\n _tmp = {}\n previous = None\n for perm in perms:\n if previous is None:\n _tmp[_PRIVILEGES_MAP[perm]] = False\n previous = _PRIVILEGES_MAP[perm]\n else:\n if perm == '*':\n _tmp[previous] = True\n else:\n _tmp[_PRIVILEGES_MAP[perm]] = False\n previous = _PRIVILEGES_MAP[perm]\n return _tmp\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
has_default_privileges
python
def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False
.. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2956-L3071
[ "def _get_object_owner(name,\n object_type,\n prepend='public',\n maintenance_db=None,\n user=None,\n host=None,\n port=None,\n password=None,\n runas=None):\n '''\n Return the owner of a postgres object\n '''\n if object_type == 'table':\n query = (' '.join([\n 'SELECT tableowner AS name',\n 'FROM pg_tables',\n \"WHERE schemaname = '{0}'\",\n \"AND tablename = '{1}'\"\n ])).format(prepend, name)\n elif object_type == 'sequence':\n query = (' '.join([\n 'SELECT rolname AS name',\n 'FROM pg_catalog.pg_class c',\n 'JOIN pg_roles r',\n 'ON c.relowner = r.oid',\n 'JOIN pg_catalog.pg_namespace n',\n 'ON n.oid = c.relnamespace',\n \"WHERE relkind='S'\",\n \"AND nspname='{0}'\",\n \"AND relname = '{1}'\",\n ])).format(prepend, name)\n elif object_type == 'schema':\n query = (' '.join([\n 'SELECT rolname AS name',\n 'FROM pg_namespace n',\n 'JOIN pg_roles r',\n 'ON n.nspowner = r.oid',\n \"WHERE nspname = '{0}'\",\n ])).format(name)\n elif object_type == 'function':\n query = (' '.join([\n 'SELECT proname AS name',\n 'FROM pg_catalog.pg_proc p',\n 'JOIN pg_catalog.pg_namespace n',\n 'ON n.oid = p.pronamespace',\n \"WHERE nspname = '{0}'\",\n \"AND p.oid::regprocedure::text = '{1}'\",\n 'ORDER BY proname, proargtypes',\n ])).format(prepend, name)\n elif object_type == 'tablespace':\n query = (' '.join([\n 'SELECT rolname AS name',\n 'FROM pg_tablespace t',\n 'JOIN pg_roles r',\n 'ON t.spcowner = r.oid',\n \"WHERE spcname = '{0}'\",\n ])).format(name)\n elif object_type == 'language':\n query = (' '.join([\n 'SELECT rolname AS name',\n 'FROM pg_language l',\n 'JOIN pg_roles r',\n 'ON l.lanowner = r.oid',\n \"WHERE lanname = '{0}'\",\n ])).format(name)\n elif object_type == 'database':\n query = (' '.join([\n 'SELECT rolname AS name',\n 'FROM pg_database d',\n 'JOIN pg_roles r',\n 'ON d.datdba = r.oid',\n \"WHERE datname = '{0}'\",\n ])).format(name)\n\n rows = psql_query(\n query,\n runas=runas,\n host=host,\n user=user,\n port=port,\n maintenance_db=maintenance_db,\n password=password)\n try:\n ret = rows[0]['name']\n except IndexError:\n ret = None\n\n return ret\n", "def _validate_default_privileges(object_type, defprivs, defprivileges):\n '''\n Validate the supplied privileges\n '''\n if object_type != 'group':\n _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm]\n for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]]\n _defperms.append('ALL')\n\n if object_type not in _DEFAULT_PRIVILEGES_OBJECTS:\n raise SaltInvocationError(\n 'Invalid object_type: {0} provided'.format(object_type))\n\n if not set(defprivs).issubset(set(_defperms)):\n raise SaltInvocationError(\n 'Invalid default privilege(s): {0} provided for object {1}'.format(\n defprivileges, object_type))\n else:\n if defprivileges:\n raise SaltInvocationError(\n 'The default privileges option should not '\n 'be set for object_type group')\n", "def _mod_defpriv_opts(object_type, defprivileges):\n '''\n Format options\n '''\n object_type = object_type.lower()\n defprivileges = '' if defprivileges is None else defprivileges\n _defprivs = re.split(r'\\s?,\\s?', defprivileges.upper())\n\n return object_type, defprivileges, _defprivs\n", "def default_privileges_list(\n name,\n object_type,\n prepend='public',\n maintenance_db=None,\n user=None,\n host=None,\n port=None,\n password=None,\n runas=None):\n '''\n .. versionadded:: 2019.0.0\n\n Return a list of default privileges for the specified object.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name\n\n name\n Name of the object for which the permissions should be returned\n\n object_type\n The object type, which can be one of the following:\n\n - table\n - sequence\n - schema\n - group\n - function\n\n prepend\n Table and Sequence object types live under a schema so this should be\n provided if the object is not under the default `public` schema\n\n maintenance_db\n The database to connect to\n\n user\n database username if different from config or default\n\n password\n user password if any password for a specified user\n\n host\n Database host if different from config or default\n\n port\n Database port if different from config or default\n\n runas\n System user all operations should be performed on behalf of\n '''\n object_type = object_type.lower()\n query = _make_default_privileges_list_query(name, object_type, prepend)\n\n if object_type not in _DEFAULT_PRIVILEGES_OBJECTS:\n raise SaltInvocationError(\n 'Invalid object_type: {0} provided'.format(object_type))\n\n rows = psql_query(\n query,\n runas=runas,\n host=host,\n user=user,\n port=port,\n maintenance_db=maintenance_db,\n password=password)\n\n ret = {}\n\n for row in rows:\n if object_type != 'group':\n result = row['name']\n result = result.strip('{}')\n parts = result.split(',')\n for part in parts:\n perms_part, _ = part.split('/')\n rolename, defperms = perms_part.split('=')\n if rolename == '':\n rolename = 'public'\n _tmp = _process_defpriv_part(defperms)\n ret[rolename] = _tmp\n else:\n if row['admin_option'] == 't':\n admin_option = True\n else:\n admin_option = False\n\n ret[row['rolname']] = admin_option\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
has_privileges
python
def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False
.. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3074-L3194
[ "def _get_object_owner(name,\n object_type,\n prepend='public',\n maintenance_db=None,\n user=None,\n host=None,\n port=None,\n password=None,\n runas=None):\n '''\n Return the owner of a postgres object\n '''\n if object_type == 'table':\n query = (' '.join([\n 'SELECT tableowner AS name',\n 'FROM pg_tables',\n \"WHERE schemaname = '{0}'\",\n \"AND tablename = '{1}'\"\n ])).format(prepend, name)\n elif object_type == 'sequence':\n query = (' '.join([\n 'SELECT rolname AS name',\n 'FROM pg_catalog.pg_class c',\n 'JOIN pg_roles r',\n 'ON c.relowner = r.oid',\n 'JOIN pg_catalog.pg_namespace n',\n 'ON n.oid = c.relnamespace',\n \"WHERE relkind='S'\",\n \"AND nspname='{0}'\",\n \"AND relname = '{1}'\",\n ])).format(prepend, name)\n elif object_type == 'schema':\n query = (' '.join([\n 'SELECT rolname AS name',\n 'FROM pg_namespace n',\n 'JOIN pg_roles r',\n 'ON n.nspowner = r.oid',\n \"WHERE nspname = '{0}'\",\n ])).format(name)\n elif object_type == 'function':\n query = (' '.join([\n 'SELECT proname AS name',\n 'FROM pg_catalog.pg_proc p',\n 'JOIN pg_catalog.pg_namespace n',\n 'ON n.oid = p.pronamespace',\n \"WHERE nspname = '{0}'\",\n \"AND p.oid::regprocedure::text = '{1}'\",\n 'ORDER BY proname, proargtypes',\n ])).format(prepend, name)\n elif object_type == 'tablespace':\n query = (' '.join([\n 'SELECT rolname AS name',\n 'FROM pg_tablespace t',\n 'JOIN pg_roles r',\n 'ON t.spcowner = r.oid',\n \"WHERE spcname = '{0}'\",\n ])).format(name)\n elif object_type == 'language':\n query = (' '.join([\n 'SELECT rolname AS name',\n 'FROM pg_language l',\n 'JOIN pg_roles r',\n 'ON l.lanowner = r.oid',\n \"WHERE lanname = '{0}'\",\n ])).format(name)\n elif object_type == 'database':\n query = (' '.join([\n 'SELECT rolname AS name',\n 'FROM pg_database d',\n 'JOIN pg_roles r',\n 'ON d.datdba = r.oid',\n \"WHERE datname = '{0}'\",\n ])).format(name)\n\n rows = psql_query(\n query,\n runas=runas,\n host=host,\n user=user,\n port=port,\n maintenance_db=maintenance_db,\n password=password)\n try:\n ret = rows[0]['name']\n except IndexError:\n ret = None\n\n return ret\n", "def _validate_privileges(object_type, privs, privileges):\n '''\n Validate the supplied privileges\n '''\n if object_type != 'group':\n _perms = [_PRIVILEGES_MAP[perm]\n for perm in _PRIVILEGE_TYPE_MAP[object_type]]\n _perms.append('ALL')\n\n if object_type not in _PRIVILEGES_OBJECTS:\n raise SaltInvocationError(\n 'Invalid object_type: {0} provided'.format(object_type))\n\n if not set(privs).issubset(set(_perms)):\n raise SaltInvocationError(\n 'Invalid privilege(s): {0} provided for object {1}'.format(\n privileges, object_type))\n else:\n if privileges:\n raise SaltInvocationError(\n 'The privileges option should not '\n 'be set for object_type group')\n", "def _mod_priv_opts(object_type, privileges):\n '''\n Format options\n '''\n object_type = object_type.lower()\n privileges = '' if privileges is None else privileges\n _privs = re.split(r'\\s?,\\s?', privileges.upper())\n\n return object_type, privileges, _privs\n", "def privileges_list(\n name,\n object_type,\n prepend='public',\n maintenance_db=None,\n user=None,\n host=None,\n port=None,\n password=None,\n runas=None):\n '''\n .. versionadded:: 2016.3.0\n\n Return a list of privileges for the specified object.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.privileges_list table_name table maintenance_db=db_name\n\n name\n Name of the object for which the permissions should be returned\n\n object_type\n The object type, which can be one of the following:\n\n - table\n - sequence\n - schema\n - tablespace\n - language\n - database\n - group\n - function\n\n prepend\n Table and Sequence object types live under a schema so this should be\n provided if the object is not under the default `public` schema\n\n maintenance_db\n The database to connect to\n\n user\n database username if different from config or default\n\n password\n user password if any password for a specified user\n\n host\n Database host if different from config or default\n\n port\n Database port if different from config or default\n\n runas\n System user all operations should be performed on behalf of\n '''\n object_type = object_type.lower()\n query = _make_privileges_list_query(name, object_type, prepend)\n\n if object_type not in _PRIVILEGES_OBJECTS:\n raise SaltInvocationError(\n 'Invalid object_type: {0} provided'.format(object_type))\n\n rows = psql_query(\n query,\n runas=runas,\n host=host,\n user=user,\n port=port,\n maintenance_db=maintenance_db,\n password=password)\n\n ret = {}\n\n for row in rows:\n if object_type != 'group':\n result = row['name']\n result = result.strip('{}')\n parts = result.split(',')\n for part in parts:\n perms_part, _ = part.split('/')\n rolename, perms = perms_part.split('=')\n if rolename == '':\n rolename = 'public'\n _tmp = _process_priv_part(perms)\n ret[rolename] = _tmp\n else:\n if row['admin_option'] == 't':\n admin_option = True\n else:\n admin_option = False\n\n ret[row['rolname']] = admin_option\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
default_privileges_grant
python
def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0
.. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3197-L3328
[ "def _psql_prepare_and_run(cmd,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None,\n user=None):\n rcmd = _psql_cmd(\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n *cmd)\n cmdret = _run_psql(\n rcmd, runas=runas, password=password, host=host, port=port, user=user)\n return cmdret\n", "def _validate_default_privileges(object_type, defprivs, defprivileges):\n '''\n Validate the supplied privileges\n '''\n if object_type != 'group':\n _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm]\n for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]]\n _defperms.append('ALL')\n\n if object_type not in _DEFAULT_PRIVILEGES_OBJECTS:\n raise SaltInvocationError(\n 'Invalid object_type: {0} provided'.format(object_type))\n\n if not set(defprivs).issubset(set(_defperms)):\n raise SaltInvocationError(\n 'Invalid default privilege(s): {0} provided for object {1}'.format(\n defprivileges, object_type))\n else:\n if defprivileges:\n raise SaltInvocationError(\n 'The default privileges option should not '\n 'be set for object_type group')\n", "def _mod_defpriv_opts(object_type, defprivileges):\n '''\n Format options\n '''\n object_type = object_type.lower()\n defprivileges = '' if defprivileges is None else defprivileges\n _defprivs = re.split(r'\\s?,\\s?', defprivileges.upper())\n\n return object_type, defprivileges, _defprivs\n", "def has_default_privileges(name,\n object_name,\n object_type,\n defprivileges=None,\n grant_option=None,\n prepend='public',\n maintenance_db=None,\n user=None,\n host=None,\n port=None,\n password=None,\n runas=None):\n '''\n .. versionadded:: 2019.0.0\n\n Check if a role has the specified privileges on an object\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.has_default_privileges user_name table_name table \\\\\n SELECT,INSERT maintenance_db=db_name\n\n name\n Name of the role whose privileges should be checked on object_type\n\n object_name\n Name of the object on which the check is to be performed\n\n object_type\n The object type, which can be one of the following:\n\n - table\n - sequence\n - schema\n - group\n - function\n\n privileges\n Comma separated list of privileges to check, from the list below:\n\n - INSERT\n - CREATE\n - TRUNCATE\n - TRIGGER\n - SELECT\n - USAGE\n - UPDATE\n - EXECUTE\n - REFERENCES\n - DELETE\n - ALL\n\n grant_option\n If grant_option is set to True, the grant option check is performed\n\n prepend\n Table and Sequence object types live under a schema so this should be\n provided if the object is not under the default `public` schema\n\n maintenance_db\n The database to connect to\n\n user\n database username if different from config or default\n\n password\n user password if any password for a specified user\n\n host\n Database host if different from config or default\n\n port\n Database port if different from config or default\n\n runas\n System user all operations should be performed on behalf of\n '''\n object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges)\n\n _validate_default_privileges(object_type, _defprivs, defprivileges)\n\n if object_type != 'group':\n owner = _get_object_owner(object_name, object_type, prepend=prepend,\n maintenance_db=maintenance_db, user=user, host=host, port=port,\n password=password, runas=runas)\n if owner is not None and name == owner:\n return True\n\n _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend,\n maintenance_db=maintenance_db, user=user, host=host, port=port,\n password=password, runas=runas)\n\n if name in _defprivileges:\n if object_type == 'group':\n if grant_option:\n retval = _defprivileges[name]\n else:\n retval = True\n return retval\n else:\n _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]\n if grant_option:\n defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms)\n retval = defperms == _defprivileges[name]\n else:\n defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms]\n if 'ALL' in _defprivs:\n retval = sorted(defperms) == sorted(_defprivileges[name].keys())\n else:\n retval = set(_defprivs).issubset(\n set(_defprivileges[name].keys()))\n return retval\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
default_privileges_revoke
python
def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0
.. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3331-L3434
[ "def _psql_prepare_and_run(cmd,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None,\n user=None):\n rcmd = _psql_cmd(\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n *cmd)\n cmdret = _run_psql(\n rcmd, runas=runas, password=password, host=host, port=port, user=user)\n return cmdret\n", "def _validate_default_privileges(object_type, defprivs, defprivileges):\n '''\n Validate the supplied privileges\n '''\n if object_type != 'group':\n _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm]\n for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]]\n _defperms.append('ALL')\n\n if object_type not in _DEFAULT_PRIVILEGES_OBJECTS:\n raise SaltInvocationError(\n 'Invalid object_type: {0} provided'.format(object_type))\n\n if not set(defprivs).issubset(set(_defperms)):\n raise SaltInvocationError(\n 'Invalid default privilege(s): {0} provided for object {1}'.format(\n defprivileges, object_type))\n else:\n if defprivileges:\n raise SaltInvocationError(\n 'The default privileges option should not '\n 'be set for object_type group')\n", "def _mod_defpriv_opts(object_type, defprivileges):\n '''\n Format options\n '''\n object_type = object_type.lower()\n defprivileges = '' if defprivileges is None else defprivileges\n _defprivs = re.split(r'\\s?,\\s?', defprivileges.upper())\n\n return object_type, defprivileges, _defprivs\n", "def has_default_privileges(name,\n object_name,\n object_type,\n defprivileges=None,\n grant_option=None,\n prepend='public',\n maintenance_db=None,\n user=None,\n host=None,\n port=None,\n password=None,\n runas=None):\n '''\n .. versionadded:: 2019.0.0\n\n Check if a role has the specified privileges on an object\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.has_default_privileges user_name table_name table \\\\\n SELECT,INSERT maintenance_db=db_name\n\n name\n Name of the role whose privileges should be checked on object_type\n\n object_name\n Name of the object on which the check is to be performed\n\n object_type\n The object type, which can be one of the following:\n\n - table\n - sequence\n - schema\n - group\n - function\n\n privileges\n Comma separated list of privileges to check, from the list below:\n\n - INSERT\n - CREATE\n - TRUNCATE\n - TRIGGER\n - SELECT\n - USAGE\n - UPDATE\n - EXECUTE\n - REFERENCES\n - DELETE\n - ALL\n\n grant_option\n If grant_option is set to True, the grant option check is performed\n\n prepend\n Table and Sequence object types live under a schema so this should be\n provided if the object is not under the default `public` schema\n\n maintenance_db\n The database to connect to\n\n user\n database username if different from config or default\n\n password\n user password if any password for a specified user\n\n host\n Database host if different from config or default\n\n port\n Database port if different from config or default\n\n runas\n System user all operations should be performed on behalf of\n '''\n object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges)\n\n _validate_default_privileges(object_type, _defprivs, defprivileges)\n\n if object_type != 'group':\n owner = _get_object_owner(object_name, object_type, prepend=prepend,\n maintenance_db=maintenance_db, user=user, host=host, port=port,\n password=password, runas=runas)\n if owner is not None and name == owner:\n return True\n\n _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend,\n maintenance_db=maintenance_db, user=user, host=host, port=port,\n password=password, runas=runas)\n\n if name in _defprivileges:\n if object_type == 'group':\n if grant_option:\n retval = _defprivileges[name]\n else:\n retval = True\n return retval\n else:\n _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]\n if grant_option:\n defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms)\n retval = defperms == _defprivileges[name]\n else:\n defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms]\n if 'ALL' in _defprivs:\n retval = sorted(defperms) == sorted(_defprivileges[name].keys())\n else:\n retval = set(_defprivs).issubset(\n set(_defprivileges[name].keys()))\n return retval\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
privileges_grant
python
def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0
.. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3437-L3573
[ "def _psql_prepare_and_run(cmd,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None,\n user=None):\n rcmd = _psql_cmd(\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n *cmd)\n cmdret = _run_psql(\n rcmd, runas=runas, password=password, host=host, port=port, user=user)\n return cmdret\n", "def _validate_privileges(object_type, privs, privileges):\n '''\n Validate the supplied privileges\n '''\n if object_type != 'group':\n _perms = [_PRIVILEGES_MAP[perm]\n for perm in _PRIVILEGE_TYPE_MAP[object_type]]\n _perms.append('ALL')\n\n if object_type not in _PRIVILEGES_OBJECTS:\n raise SaltInvocationError(\n 'Invalid object_type: {0} provided'.format(object_type))\n\n if not set(privs).issubset(set(_perms)):\n raise SaltInvocationError(\n 'Invalid privilege(s): {0} provided for object {1}'.format(\n privileges, object_type))\n else:\n if privileges:\n raise SaltInvocationError(\n 'The privileges option should not '\n 'be set for object_type group')\n", "def _mod_priv_opts(object_type, privileges):\n '''\n Format options\n '''\n object_type = object_type.lower()\n privileges = '' if privileges is None else privileges\n _privs = re.split(r'\\s?,\\s?', privileges.upper())\n\n return object_type, privileges, _privs\n", "def has_privileges(name,\n object_name,\n object_type,\n privileges=None,\n grant_option=None,\n prepend='public',\n maintenance_db=None,\n user=None,\n host=None,\n port=None,\n password=None,\n runas=None):\n '''\n .. versionadded:: 2016.3.0\n\n Check if a role has the specified privileges on an object\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.has_privileges user_name table_name table \\\\\n SELECT,INSERT maintenance_db=db_name\n\n name\n Name of the role whose privileges should be checked on object_type\n\n object_name\n Name of the object on which the check is to be performed\n\n object_type\n The object type, which can be one of the following:\n\n - table\n - sequence\n - schema\n - tablespace\n - language\n - database\n - group\n - function\n\n privileges\n Comma separated list of privileges to check, from the list below:\n\n - INSERT\n - CREATE\n - TRUNCATE\n - CONNECT\n - TRIGGER\n - SELECT\n - USAGE\n - TEMPORARY\n - UPDATE\n - EXECUTE\n - REFERENCES\n - DELETE\n - ALL\n\n grant_option\n If grant_option is set to True, the grant option check is performed\n\n prepend\n Table and Sequence object types live under a schema so this should be\n provided if the object is not under the default `public` schema\n\n maintenance_db\n The database to connect to\n\n user\n database username if different from config or default\n\n password\n user password if any password for a specified user\n\n host\n Database host if different from config or default\n\n port\n Database port if different from config or default\n\n runas\n System user all operations should be performed on behalf of\n '''\n object_type, privileges, _privs = _mod_priv_opts(object_type, privileges)\n\n _validate_privileges(object_type, _privs, privileges)\n\n if object_type != 'group':\n owner = _get_object_owner(object_name, object_type, prepend=prepend,\n maintenance_db=maintenance_db, user=user, host=host, port=port,\n password=password, runas=runas)\n if owner is not None and name == owner:\n return True\n\n _privileges = privileges_list(object_name, object_type, prepend=prepend,\n maintenance_db=maintenance_db, user=user, host=host, port=port,\n password=password, runas=runas)\n\n if name in _privileges:\n if object_type == 'group':\n if grant_option:\n retval = _privileges[name]\n else:\n retval = True\n return retval\n else:\n _perms = _PRIVILEGE_TYPE_MAP[object_type]\n if grant_option:\n perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms)\n retval = perms == _privileges[name]\n else:\n perms = [_PRIVILEGES_MAP[perm] for perm in _perms]\n if 'ALL' in _privs:\n retval = sorted(perms) == sorted(_privileges[name].keys())\n else:\n retval = set(_privs).issubset(\n set(_privileges[name].keys()))\n return retval\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
privileges_revoke
python
def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0
.. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3576-L3684
[ "def _psql_prepare_and_run(cmd,\n host=None,\n port=None,\n maintenance_db=None,\n password=None,\n runas=None,\n user=None):\n rcmd = _psql_cmd(\n host=host, user=user, port=port,\n maintenance_db=maintenance_db,\n *cmd)\n cmdret = _run_psql(\n rcmd, runas=runas, password=password, host=host, port=port, user=user)\n return cmdret\n", "def _validate_privileges(object_type, privs, privileges):\n '''\n Validate the supplied privileges\n '''\n if object_type != 'group':\n _perms = [_PRIVILEGES_MAP[perm]\n for perm in _PRIVILEGE_TYPE_MAP[object_type]]\n _perms.append('ALL')\n\n if object_type not in _PRIVILEGES_OBJECTS:\n raise SaltInvocationError(\n 'Invalid object_type: {0} provided'.format(object_type))\n\n if not set(privs).issubset(set(_perms)):\n raise SaltInvocationError(\n 'Invalid privilege(s): {0} provided for object {1}'.format(\n privileges, object_type))\n else:\n if privileges:\n raise SaltInvocationError(\n 'The privileges option should not '\n 'be set for object_type group')\n", "def _mod_priv_opts(object_type, privileges):\n '''\n Format options\n '''\n object_type = object_type.lower()\n privileges = '' if privileges is None else privileges\n _privs = re.split(r'\\s?,\\s?', privileges.upper())\n\n return object_type, privileges, _privs\n", "def has_privileges(name,\n object_name,\n object_type,\n privileges=None,\n grant_option=None,\n prepend='public',\n maintenance_db=None,\n user=None,\n host=None,\n port=None,\n password=None,\n runas=None):\n '''\n .. versionadded:: 2016.3.0\n\n Check if a role has the specified privileges on an object\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.has_privileges user_name table_name table \\\\\n SELECT,INSERT maintenance_db=db_name\n\n name\n Name of the role whose privileges should be checked on object_type\n\n object_name\n Name of the object on which the check is to be performed\n\n object_type\n The object type, which can be one of the following:\n\n - table\n - sequence\n - schema\n - tablespace\n - language\n - database\n - group\n - function\n\n privileges\n Comma separated list of privileges to check, from the list below:\n\n - INSERT\n - CREATE\n - TRUNCATE\n - CONNECT\n - TRIGGER\n - SELECT\n - USAGE\n - TEMPORARY\n - UPDATE\n - EXECUTE\n - REFERENCES\n - DELETE\n - ALL\n\n grant_option\n If grant_option is set to True, the grant option check is performed\n\n prepend\n Table and Sequence object types live under a schema so this should be\n provided if the object is not under the default `public` schema\n\n maintenance_db\n The database to connect to\n\n user\n database username if different from config or default\n\n password\n user password if any password for a specified user\n\n host\n Database host if different from config or default\n\n port\n Database port if different from config or default\n\n runas\n System user all operations should be performed on behalf of\n '''\n object_type, privileges, _privs = _mod_priv_opts(object_type, privileges)\n\n _validate_privileges(object_type, _privs, privileges)\n\n if object_type != 'group':\n owner = _get_object_owner(object_name, object_type, prepend=prepend,\n maintenance_db=maintenance_db, user=user, host=host, port=port,\n password=password, runas=runas)\n if owner is not None and name == owner:\n return True\n\n _privileges = privileges_list(object_name, object_type, prepend=prepend,\n maintenance_db=maintenance_db, user=user, host=host, port=port,\n password=password, runas=runas)\n\n if name in _privileges:\n if object_type == 'group':\n if grant_option:\n retval = _privileges[name]\n else:\n retval = True\n return retval\n else:\n _perms = _PRIVILEGE_TYPE_MAP[object_type]\n if grant_option:\n perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms)\n retval = perms == _privileges[name]\n else:\n perms = [_PRIVILEGES_MAP[perm] for perm in _perms]\n if 'ALL' in _privs:\n retval = sorted(perms) == sorted(_privileges[name].keys())\n else:\n retval = set(_privs).issubset(\n set(_privileges[name].keys()))\n return retval\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
datadir_init
python
def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0
.. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3687-L3754
[ "def datadir_exists(name):\n '''\n .. versionadded:: 2016.3.0\n\n Checks if postgres data directory has been initialized\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' postgres.datadir_exists '/var/lib/pgsql/data'\n\n name\n Name of the directory to check\n '''\n _version_file = os.path.join(name, 'PG_VERSION')\n _config_file = os.path.join(name, 'postgresql.conf')\n\n return os.path.isfile(_version_file) and os.path.isfile(_config_file)\n" ]
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
saltstack/salt
salt/modules/postgres.py
datadir_exists
python
def datadir_exists(name): ''' .. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check ''' _version_file = os.path.join(name, 'PG_VERSION') _config_file = os.path.join(name, 'postgresql.conf') return os.path.isfile(_version_file) and os.path.isfile(_config_file)
.. versionadded:: 2016.3.0 Checks if postgres data directory has been initialized CLI Example: .. code-block:: bash salt '*' postgres.datadir_exists '/var/lib/pgsql/data' name Name of the directory to check
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3757-L3775
null
# -*- coding: utf-8 -*- ''' Module to provide Postgres compatibility to salt. :configuration: In order to connect to Postgres, certain configuration is required in /etc/salt/minion on the relevant minions. Some sample configs might look like:: postgres.host: 'localhost' postgres.port: '5432' postgres.user: 'postgres' -> db user postgres.pass: '' postgres.maintenance_db: 'postgres' The default for the maintenance_db is 'postgres' and in most cases it can be left at the default setting. This data can also be passed into pillar. Options passed into opts will overwrite options passed into pillar :note: This module uses MD5 hashing which may not be compliant with certain security audits. :note: When installing postgres from the official postgres repos, on certain linux distributions, either the psql or the initdb binary is *not* automatically placed on the path. Add a configuration to the location of the postgres bin's path to the relevant minion for this module:: postgres.bins_dir: '/usr/pgsql-9.5/bin/' ''' # This pylint error is popping up where there are no colons? # pylint: disable=E8203 # Import python libs from __future__ import absolute_import, unicode_literals, print_function import datetime import logging import hashlib import os import re import pipes import tempfile try: import csv HAS_CSV = True except ImportError: HAS_CSV = False # Import salt libs import salt.utils.files import salt.utils.itertools import salt.utils.odict import salt.utils.path import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.versions import LooseVersion as _LooseVersion # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import StringIO log = logging.getLogger(__name__) _DEFAULT_PASSWORDS_ENCRYPTION = True _EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED' _EXTENSION_INSTALLED = 'EXTENSION INSTALLED' _EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE' _EXTENSION_TO_MOVE = 'EXTENSION TO MOVE' _EXTENSION_FLAGS = ( _EXTENSION_NOT_INSTALLED, _EXTENSION_INSTALLED, _EXTENSION_TO_UPGRADE, _EXTENSION_TO_MOVE, ) _PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 'c': 'CONNECT', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'T': 'TEMPORARY', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_MAP = { 'a': 'INSERT', 'C': 'CREATE', 'D': 'TRUNCATE', 't': 'TRIGGER', 'r': 'SELECT', 'U': 'USAGE', 'w': 'UPDATE', 'X': 'EXECUTE', 'x': 'REFERENCES', 'd': 'DELETE', '*': 'GRANT', } _DEFAULT_PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'sequence', 'table', 'group', 'function', ) ) _PRIVILEGES_OBJECTS = frozenset( ( 'schema', 'tablespace', 'language', 'sequence', 'table', 'group', 'database', 'function', ) ) _PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'tablespace': 'C', 'language': 'U', 'sequence': 'rwU', 'schema': 'UC', 'database': 'CTc', 'function': 'X', } _DEFAULT_PRIVILEGE_TYPE_MAP = { 'table': 'arwdDxt', 'sequence': 'rwU', 'schema': 'UC', 'function': 'X', } def __virtual__(): ''' Only load this module if the psql bin exist. initdb bin might also be used, but its presence will be detected on runtime. ''' utils = ['psql'] if not HAS_CSV: return False for util in utils: if not salt.utils.path.which(util): if not _find_pg_binary(util): return (False, '{0} was not found'.format(util)) return True def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.path.which(os.path.join(pg_bin_dir, util)) else: return util_bin def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None): ''' Helper function to call psql, because the password requirement makes this too much code to be repeated in each function below ''' kwargs = { 'reset_system_locale': False, 'clean_env': True, } if runas is None: if not host: host = __salt__['config.option']('postgres.host') if not host or host.startswith('/'): if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas if runas: kwargs['runas'] = runas if password is None: password = __salt__['config.option']('postgres.pass') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format( 'localhost' if not host or host.startswith('/') else host, port if port else '*', user if user else '*', password, ))) __salt__['file.chown'](pgpassfile, runas, '') kwargs['env'] = {'PGPASSFILE': pgpassfile} ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error connecting to Postgresql server') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Remove PGPASSFILE failed') return ret def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family']: runas = 'pgsql' elif 'OpenBSD' in __grains__['os_family']: runas = '_postgresql' else: runas = 'postgres' if user is None: user = runas _INITDB_BIN = _find_pg_binary('initdb') if not _INITDB_BIN: raise CommandExecutionError('initdb executable not found.') cmd = [ _INITDB_BIN, '--pgdata={0}'.format(name), '--username={0}'.format(user), '--auth={0}'.format(auth), '--encoding={0}'.format(encoding), ] if locale is not None: cmd.append('--locale={0}'.format(locale)) # intentionally use short option, as the long option name has been # renamed from "xlogdir" to "waldir" in PostgreSQL 10 if waldir is not None: cmd.append('-X') cmd.append(waldir) if checksums: cmd.append('--data-checksums') if password is not None: pgpassfile = salt.utils.files.mkstemp(text=True) with salt.utils.files.fopen(pgpassfile, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str('{0}'.format(password))) __salt__['file.chown'](pgpassfile, runas, '') cmd.extend([ '--pwfile={0}'.format(pgpassfile), ]) kwargs = dict(runas=runas, clean_env=True) cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs) if ret.get('retcode', 0) != 0: log.error('Error initilizing the postgres data directory') if password is not None and not __salt__['file.remove'](pgpassfile): log.warning('Removal of PGPASSFILE failed') return ret def version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return the version of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.version ''' query = 'SELECT setting FROM pg_catalog.pg_settings ' \ 'WHERE name = \'server_version\'' cmd = _psql_cmd('-c', query, '-t', host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = _run_psql( cmd, runas=runas, password=password, host=host, port=port, user=user) for line in salt.utils.itertools.split(ret['stdout'], '\n'): # Just return the first line return line def _parsed_version(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Returns the server version properly parsed and int casted for internal use. If the Postgres server does not respond, None will be returned. ''' psql_version = version( user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, ) if psql_version: return _LooseVersion(psql_version) else: log.warning('Attempt to parse version of Postgres server failed. ' 'Is the server responding?') return None def _connection_defaults(user=None, host=None, port=None, maintenance_db=None): ''' Returns a tuple of (user, host, port, db) with config, pillar, or default values assigned to missing values. ''' if not user: user = __salt__['config.option']('postgres.user') if not host: host = __salt__['config.option']('postgres.host') if not port: port = __salt__['config.option']('postgres.port') if not maintenance_db: maintenance_db = __salt__['config.option']('postgres.maintenance_db') return (user, host, port, maintenance_db) def _psql_cmd(*args, **kwargs): ''' Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command. ''' (user, host, port, maintenance_db) = _connection_defaults( kwargs.get('user'), kwargs.get('host'), kwargs.get('port'), kwargs.get('maintenance_db')) _PSQL_BIN = _find_pg_binary('psql') cmd = [_PSQL_BIN, '--no-align', '--no-readline', '--no-psqlrc', '--no-password'] # Never prompt, handled in _run_psql. if user: cmd += ['--username', user] if host: cmd += ['--host', host] if port: cmd += ['--port', six.text_type(port)] if not maintenance_db: maintenance_db = 'postgres' cmd.extend(['--dbname', maintenance_db]) cmd.extend(args) return cmd def _psql_prepare_and_run(cmd, host=None, port=None, maintenance_db=None, password=None, runas=None, user=None): rcmd = _psql_cmd( host=host, user=user, port=port, maintenance_db=maintenance_db, *cmd) cmdret = _run_psql( rcmd, runas=runas, password=password, host=host, port=port, user=user) return cmdret def psql_query(query, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, write=False): ''' Run an SQL-Query and return the results as a list. This command only supports SELECT statements. This limitation can be worked around with a query like this: WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated; query The query string. user Database username, if different from config or default. host Database host, if different from config or default. port Database port, if different from the config or default. maintenance_db The database to run the query against. password User password, if different from the config or default. runas User to run the command as. write Mark query as READ WRITE transaction. CLI Example: .. code-block:: bash salt '*' postgres.psql_query 'select * from pg_stat_activity' ''' ret = [] csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format( query.strip().rstrip(';')) # Mark transaction as R/W to achieve write will be allowed # Commit is necessary due to transaction if write: csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query) # always use the same datestyle settings to allow parsing dates # regardless what server settings are configured cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY', '-c', csv_query], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if cmdret['retcode'] > 0: return ret csv_file = StringIO(cmdret['stdout']) header = {} for row in csv.reader(csv_file, delimiter=salt.utils.stringutils.to_str(','), quotechar=salt.utils.stringutils.to_str('"')): if not row: continue if not header: header = row continue ret.append(dict(zip(header, row))) # Remove 'COMMIT' message if query is inside R/W transction if write: ret = ret[0:-1] return ret # Database related actions def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELECT datname as "Name", pga.rolname as "Owner", ' 'pg_encoding_to_char(encoding) as "Encoding", ' 'datcollate as "Collate", datctype as "Ctype", ' 'datacl as "Access privileges", spcname as "Tablespace" ' 'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts ' 'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace' ) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def db_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a database exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_exists 'dbname' ''' databases = db_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in databases # TODO properly implemented escaping def _quote_ddl_value(value, quote="'"): if value is None: return None if quote in value: # detect trivial sqli raise SaltInvocationError( 'Unsupported character {0} in value: {1}'.format(quote, value)) return "{quote}{value}{quote}".format(quote=quote, value=value) def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, template=None, runas=None): ''' Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis ''' # Base query to create a database query = 'CREATE DATABASE "{0}"'.format(name) # "With"-options to create a database with_args = salt.utils.odict.OrderedDict([ ('TABLESPACE', _quote_ddl_value(tablespace, '"')), # owner needs to be enclosed in double quotes so postgres # doesn't get thrown by dashes in the name ('OWNER', _quote_ddl_value(owner, '"')), ('TEMPLATE', template), ('ENCODING', _quote_ddl_value(encoding)), ('LC_COLLATE', _quote_ddl_value(lc_collate)), ('LC_CTYPE', _quote_ddl_value(lc_ctype)), ]) with_chunks = [] for key, value in with_args.items(): if value is not None: with_chunks += [key, '=', value] # Build a final query if with_chunks: with_chunks.insert(0, ' WITH') query += ' '.join(with_chunks) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def db_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, owner=None, owner_recurse=False, runas=None): ''' Change tablespace or/and owner of database. CLI Example: .. code-block:: bash salt '*' postgres.db_alter dbname owner=otheruser ''' if not any((tablespace, owner)): return True # Nothing todo? if owner and owner_recurse: ret = owner_to(name, owner, user=user, host=host, port=port, password=password, runas=runas) else: queries = [] if owner: queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format( name, owner )) if tablespace: queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format( name, tablespace )) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def db_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a databases from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_remove 'dbname' ''' # db doesn't exist, proceed query = 'DROP DATABASE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # Tablespace related actions def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ''' ret = {} query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__['postgres.psql_query'](query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row ret[row['Name']].pop('Name') return ret def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a tablespace exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_exists 'dbname' .. versionadded:: 2015.8.0 ''' tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return name in tablespaces def tablespace_create(name, location, options=None, owner=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Adds a tablespace to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_create tablespacename '/path/datadir' .. versionadded:: 2015.8.0 ''' owner_query = '' options_query = '' if owner: owner_query = 'OWNER "{0}"'.format(owner) # should come out looking like: 'OWNER postgres' if options: optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)] options_query = 'WITH ( {0} )'.format(', '.join(optionstext)) # should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )' query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name, owner_query, location, options_query) # Execute the command ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None, password=None, new_name=None, new_owner=None, set_option=None, reset_option=None, runas=None): ''' Change tablespace name, owner, or options. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_alter tsname new_owner=otheruser salt '*' postgres.tablespace_alter index_space new_name=fast_raid salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}" salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost .. versionadded:: 2015.8.0 ''' if not any([new_name, new_owner, set_option, reset_option]): return True # Nothing todo? queries = [] if new_name: queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format( name, new_name)) if new_owner: queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format( name, new_owner)) if set_option: queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format( name, set_option.keys()[0], set_option.values()[0])) if reset_option: queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format( name, reset_option)) for query in queries: ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ret['retcode'] != 0: return False return True def tablespace_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a tablespace from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_remove tsname .. versionadded:: 2015.8.0 ''' query = 'DROP TABLESPACE "{0}"'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 # User related actions def user_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.user_list ''' ret = {} ver = _parsed_version(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if ver: if ver >= _LooseVersion('9.1'): replication_column = 'pg_roles.rolreplication' else: replication_column = 'NULL' if ver >= _LooseVersion('9.5'): rolcatupdate_column = 'NULL' else: rolcatupdate_column = 'pg_roles.rolcatupdate' else: log.error('Could not retrieve Postgres version. Is Postgresql server running?') return False # will return empty string if return_password = False _x = lambda s: s if return_password else '' query = (''.join([ 'SELECT ' 'pg_roles.rolname as "name",' 'pg_roles.rolsuper as "superuser", ' 'pg_roles.rolinherit as "inherits privileges", ' 'pg_roles.rolcreaterole as "can create roles", ' 'pg_roles.rolcreatedb as "can create databases", ' '{0} as "can update system catalogs", ' 'pg_roles.rolcanlogin as "can login", ' '{1} as "replication", ' 'pg_roles.rolconnlimit as "connections", ' '(SELECT array_agg(pg_roles2.rolname)' ' FROM pg_catalog.pg_auth_members' ' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)' ' WHERE pg_auth_members.member = pg_roles.oid) as "groups",' 'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", ' 'pg_roles.rolconfig as "defaults variables" ' , _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '), 'FROM pg_roles ' , _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ') , _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid') ]).format(rolcatupdate_column, replication_column)) rows = psql_query(query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) def get_bool(rowdict, key): ''' Returns the boolean value of the key, instead of 't' and 'f' strings. ''' if rowdict[key] == 't': return True elif rowdict[key] == 'f': return False else: return None for row in rows: retrow = {} for key in ('superuser', 'inherits privileges', 'can create roles', 'can create databases', 'can update system catalogs', 'can login', 'replication', 'connections'): retrow[key] = get_bool(row, key) for date_key in ('expiry time',): try: retrow[date_key] = datetime.datetime.strptime( row[date_key], '%Y-%m-%d %H:%M:%S') except ValueError: retrow[date_key] = None retrow['defaults variables'] = row['defaults variables'] if return_password: retrow['password'] = row['password'] # use csv reader to handle quoted roles correctly retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0] ret[row['name']] = retrow return ret def role_get(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None, return_password=False): ''' Return a dict with information about users of a Postgres server. Set return_password to True to get password hash in the result. CLI Example: .. code-block:: bash salt '*' postgres.role_get postgres ''' all_users = user_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=return_password) try: return all_users.get(name, None) except AttributeError: log.error('Could not retrieve Postgres role. Is Postgres running?') return None def user_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Checks if a user exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_exists 'username' ''' return bool( role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False)) def _add_role_flag(string, test, flag, cond=None, prefix='NO', addtxt='', skip=False): if not skip: if cond is None: cond = test if test is not None: if cond: string = '{0} {1}'.format(string, flag) else: string = '{0} {2}{1}'.format(string, flag, prefix) if addtxt: string = '{0} {1}'.format(string, addtxt) return string def _maybe_encrypt_password(role, password, encrypted=_DEFAULT_PASSWORDS_ENCRYPTION): ''' pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}' ''' if password is not None: password = six.text_type(password) if encrypted and password and not password.startswith('md5'): password = "md5{0}".format( hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest()) return password def _role_cmd_args(name, sub_cmd='', typ_='role', encrypted=None, login=None, connlimit=None, inherit=None, createdb=None, createroles=None, superuser=None, groups=None, replication=None, rolepassword=None, valid_until=None, db_role=None): if inherit is None: if typ_ in ['user', 'group']: inherit = True if login is None: if typ_ == 'user': login = True if typ_ == 'group': login = False # defaults to encrypted passwords (md5{password}{rolename}) if encrypted is None: encrypted = _DEFAULT_PASSWORDS_ENCRYPTION skip_passwd = False escaped_password = '' escaped_valid_until = '' if not ( rolepassword is not None # first is passwd set # second is for handling NOPASSWD and ( isinstance(rolepassword, six.string_types) and bool(rolepassword) ) or ( isinstance(rolepassword, bool) ) ): skip_passwd = True if isinstance(rolepassword, six.string_types) and bool(rolepassword): escaped_password = '\'{0}\''.format( _maybe_encrypt_password(name, rolepassword.replace('\'', '\'\''), encrypted=encrypted)) if isinstance(valid_until, six.string_types) and bool(valid_until): escaped_valid_until = '\'{0}\''.format( valid_until.replace('\'', '\'\''), ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': six.text_type(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, {'flag': 'VALID UNTIL', 'test': bool(valid_until), 'skip': valid_until is None, 'addtxt': escaped_valid_until}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, valid_until=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('%s \'%s\' already exists', typ_.capitalize(), name) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '%s \'%s\' could not be found', typ_.capitalize(), name ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=rolepassword, valid_until=valid_until, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=None, valid_until=None, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' valid_until='valid_until' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=rolepassword, valid_until=valid_until, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'%s\'.', name) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): ''' Compare versions of extensions using salt.utils.versions.LooseVersion. Returns ``True`` if version a is lesser than b. ''' return _LooseVersion(a) < _LooseVersion(b) def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: %s', name) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: %s', name) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_update(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createroles=None, encrypted=None, inherit=None, login=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres group CLI Examples: .. code-block:: bash salt '*' postgres.group_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='rolepassword' ''' return _role_update(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, typ_='group', createroles=createroles, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=rolepassword, groups=groups, runas=runas) def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.group_remove 'groupname' ''' return _role_remove(groupname, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) def owner_to(dbname, ownername, user=None, host=None, port=None, password=None, runas=None): ''' Set the owner of all schemas, functions, tables, views and sequences to the given username. CLI Example: .. code-block:: bash salt '*' postgres.owner_to 'dbname' 'username' ''' sqlfile = tempfile.NamedTemporaryFile() sqlfile.write('begin;\n') sqlfile.write( 'alter database "{0}" owner to "{1}";\n'.format( dbname, ownername ) ) queries = ( # schemas ('alter schema {n} owner to {owner};', 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;'), # tables and views ('alter table {n} owner to {owner};', 'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as ' 'n from information_schema.tables where table_schema not in ' '(\'pg_catalog\', \'information_schema\');'), # functions ('alter function {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' ' and not p.proisagg;'), # aggregate functions ('alter aggregate {n} owner to {owner};', 'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p ' 'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where ' 'ns.nspname not in (\'pg_catalog\', \'information_schema\') ' 'and p.proisagg;'), # sequences ('alter sequence {n} owner to {owner};', 'select quote_ident(sequence_schema)||\'.\'||' 'quote_ident(sequence_name) as n from information_schema.sequences;') ) for fmt, query in queries: ret = psql_query(query, user=user, host=host, port=port, maintenance_db=dbname, password=password, runas=runas) for row in ret: sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n') sqlfile.write('commit;\n') sqlfile.flush() os.chmod(sqlfile.name, 0o644) # ensure psql can read the file # run the generated sqlfile in the db cmdret = _psql_prepare_and_run(['-f', sqlfile.name], user=user, runas=runas, host=host, port=port, password=password, maintenance_db=dbname) return cmdret # Schema related actions def schema_create(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Creates a Postgres schema. CLI Example: .. code-block:: bash salt '*' postgres.schema_create dbname name owner='owner' \\ user='user' \\ db_user='user' db_password='password' db_host='hostname' db_port='port' ''' # check if schema exists if schema_exists(dbname, name, user=user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('\'%s\' already exists in \'%s\'', name, dbname) return False sub_cmd = 'CREATE SCHEMA "{0}"'.format(name) if owner is not None: sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner) ret = _psql_prepare_and_run(['-c', sub_cmd], user=db_user, password=db_password, port=db_port, host=db_host, maintenance_db=dbname, runas=user) return ret['retcode'] == 0 def schema_remove(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Removes a schema from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_remove dbname schemaname dbname Database name we work on schemaname The schema's name we'll remove user System user all operations should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' # check if schema exists if not schema_exists(dbname, name, user=None, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname) return False # schema exists, proceed sub_cmd = 'DROP SCHEMA "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=user, maintenance_db=dbname, host=db_host, user=db_user, port=db_port, password=db_password) if not schema_exists(dbname, name, user, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port): return True else: log.info('Failed to delete schema \'%s\'.', name) return False def schema_exists(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Checks if a schema exists on the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.schema_exists dbname schemaname dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' return bool( schema_get(dbname, name, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password)) def schema_get(dbname, name, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a database. CLI Example: .. code-block:: bash salt '*' postgres.schema_get dbname name dbname Database name we query on name Schema name we look for user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' all_schemas = schema_list(dbname, user=user, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password) try: return all_schemas.get(name, None) except AttributeError: log.error('Could not retrieve Postgres schema. Is Postgres running?') return False def schema_list(dbname, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Return a dict with information about schemas in a Postgres database. CLI Example: .. code-block:: bash salt '*' postgres.schema_list dbname dbname Database name we query on user The system user the operation should be performed on behalf of db_user database username if different from config or default db_password user password if any password for a specified user db_host Database host if different from config or default db_port Database port if different from config or default ''' ret = {} query = (''.join([ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ])) rows = psql_query(query, runas=user, host=db_host, user=db_user, port=db_port, maintenance_db=dbname, password=db_password) for row in rows: retrow = {} for key in ('owner', 'acl'): retrow[key] = row[key] ret[row['name']] = retrow return ret def language_list( maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of languages in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_list dbname maintenance_db The database to check user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' ret = {} query = 'SELECT lanname AS "Name" FROM pg_language' rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) for row in rows: ret[row['Name']] = row['Name'] return ret def language_exists( name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Checks if language exists in a database. CLI Example: .. code-block:: bash salt '*' postgres.language_exists plpgsql dbname name Language to check for maintenance_db The database to check in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' languages = language_list( maintenance_db, user=user, host=host, port=port, password=password, runas=runas) return name in languages def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example: .. code-block:: bash salt '*' postgres.language_create plpgsql dbname name Language to install maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if language_exists(name, maintenance_db): log.info('Language %s already exists in %s', name, maintenance_db) return False query = 'CREATE LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def language_remove(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Removes a language from a database CLI Example: .. code-block:: bash salt '*' postgres.language_remove plpgsql dbname name Language to remove maintenance_db The database to install the language in user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' if not language_exists(name, maintenance_db): log.info('Language %s does not exist in %s', name, maintenance_db) return False query = 'DROP LANGUAGE {0}'.format(name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, runas=runas, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='r'", 'ORDER BY nspname', ])).format(prepend) elif object_type == 'sequence': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='S'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid', 'ON defacl.defaclrole = aid.oid ', 'JOIN pg_namespace nsp ', 'ON nsp.oid = defacl.defaclnamespace', "WHERE nsp.nspname = '{0}'", "AND defaclobjtype ='f'", 'ORDER BY nspname', ])).format(prepend, name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _make_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'r'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT relacl AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE nspname = '{0}'", "AND relname = '{1}'", "AND relkind = 'S'", 'ORDER BY relname', ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT nspacl AS name', 'FROM pg_catalog.pg_namespace', "WHERE nspname = '{0}'", 'ORDER BY nspname', ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proacl AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT spcacl AS name', 'FROM pg_catalog.pg_tablespace', "WHERE spcname = '{0}'", 'ORDER BY spcname', ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT lanacl AS name', 'FROM pg_catalog.pg_language', "WHERE lanname = '{0}'", 'ORDER BY lanname', ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT datacl AS name', 'FROM pg_catalog.pg_database', "WHERE datname = '{0}'", 'ORDER BY datname', ])).format(name) elif object_type == 'group': query = (' '.join([ 'SELECT rolname, admin_option', 'FROM pg_catalog.pg_auth_members m', 'JOIN pg_catalog.pg_roles r', 'ON m.member=r.oid', 'WHERE m.roleid IN', '(SELECT oid', 'FROM pg_catalog.pg_roles', "WHERE rolname='{0}')", 'ORDER BY rolname', ])).format(name) return query def _get_object_owner(name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' Return the owner of a postgres object ''' if object_type == 'table': query = (' '.join([ 'SELECT tableowner AS name', 'FROM pg_tables', "WHERE schemaname = '{0}'", "AND tablename = '{1}'" ])).format(prepend, name) elif object_type == 'sequence': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_catalog.pg_class c', 'JOIN pg_roles r', 'ON c.relowner = r.oid', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = c.relnamespace', "WHERE relkind='S'", "AND nspname='{0}'", "AND relname = '{1}'", ])).format(prepend, name) elif object_type == 'schema': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_namespace n', 'JOIN pg_roles r', 'ON n.nspowner = r.oid', "WHERE nspname = '{0}'", ])).format(name) elif object_type == 'function': query = (' '.join([ 'SELECT proname AS name', 'FROM pg_catalog.pg_proc p', 'JOIN pg_catalog.pg_namespace n', 'ON n.oid = p.pronamespace', "WHERE nspname = '{0}'", "AND p.oid::regprocedure::text = '{1}'", 'ORDER BY proname, proargtypes', ])).format(prepend, name) elif object_type == 'tablespace': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_tablespace t', 'JOIN pg_roles r', 'ON t.spcowner = r.oid', "WHERE spcname = '{0}'", ])).format(name) elif object_type == 'language': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_language l', 'JOIN pg_roles r', 'ON l.lanowner = r.oid', "WHERE lanname = '{0}'", ])).format(name) elif object_type == 'database': query = (' '.join([ 'SELECT rolname AS name', 'FROM pg_database d', 'JOIN pg_roles r', 'ON d.datdba = r.oid', "WHERE datname = '{0}'", ])).format(name) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) try: ret = rows[0]['name'] except IndexError: ret = None return ret def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(defprivs).issubset(set(_defperms)): raise SaltInvocationError( 'Invalid default privilege(s): {0} provided for object {1}'.format( defprivileges, object_type)) else: if defprivileges: raise SaltInvocationError( 'The default privileges option should not ' 'be set for object_type group') def _mod_defpriv_opts(object_type, defprivileges): ''' Format options ''' object_type = object_type.lower() defprivileges = '' if defprivileges is None else defprivileges _defprivs = re.split(r'\s?,\s?', defprivileges.upper()) return object_type, defprivileges, _defprivs def _process_defpriv_part(defperms): ''' Process part ''' _tmp = {} previous = None for defperm in defperms: if previous is None: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] else: if defperm == '*': _tmp[previous] = True else: _tmp[_DEFAULT_PRIVILEGES_MAP[defperm]] = False previous = _DEFAULT_PRIVILEGES_MAP[defperm] return _tmp def _validate_privileges(object_type, privs, privileges): ''' Validate the supplied privileges ''' if object_type != 'group': _perms = [_PRIVILEGES_MAP[perm] for perm in _PRIVILEGE_TYPE_MAP[object_type]] _perms.append('ALL') if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) if not set(privs).issubset(set(_perms)): raise SaltInvocationError( 'Invalid privilege(s): {0} provided for object {1}'.format( privileges, object_type)) else: if privileges: raise SaltInvocationError( 'The privileges option should not ' 'be set for object_type group') def _mod_priv_opts(object_type, privileges): ''' Format options ''' object_type = object_type.lower() privileges = '' if privileges is None else privileges _privs = re.split(r'\s?,\s?', privileges.upper()) return object_type, privileges, _privs def _process_priv_part(perms): ''' Process part ''' _tmp = {} previous = None for perm in perms: if previous is None: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] else: if perm == '*': _tmp[previous] = True else: _tmp[_PRIVILEGES_MAP[perm]] = False previous = _PRIVILEGES_MAP[perm] return _tmp def default_privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Return a list of default privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_default_privileges_list_query(name, object_type, prepend) if object_type not in _DEFAULT_PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, defperms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_defpriv_part(defperms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def privileges_list( name, object_type, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Return a list of privileges for the specified object. CLI Example: .. code-block:: bash salt '*' postgres.privileges_list table_name table maintenance_db=db_name name Name of the object for which the permissions should be returned object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type = object_type.lower() query = _make_privileges_list_query(name, object_type, prepend) if object_type not in _PRIVILEGES_OBJECTS: raise SaltInvocationError( 'Invalid object_type: {0} provided'.format(object_type)) rows = psql_query( query, runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = {} for row in rows: if object_type != 'group': result = row['name'] result = result.strip('{}') parts = result.split(',') for part in parts: perms_part, _ = part.split('/') rolename, perms = perms_part.split('=') if rolename == '': rolename = 'public' _tmp = _process_priv_part(perms) ret[rolename] = _tmp else: if row['admin_option'] == 't': admin_option = True else: admin_option = False ret[row['rolname']] = admin_option return ret def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _defprivileges = default_privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _defprivileges: if object_type == 'group': if grant_option: retval = _defprivileges[name] else: retval = True return retval else: _defperms = _DEFAULT_PRIVILEGE_TYPE_MAP[object_type] if grant_option: defperms = dict((_DEFAULT_PRIVILEGES_MAP[defperm], True) for defperm in _defperms) retval = defperms == _defprivileges[name] else: defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _defperms] if 'ALL' in _defprivs: retval = sorted(defperms) == sorted(_defprivileges[name].keys()) else: retval = set(_defprivs).issubset( set(_defprivileges[name].keys())) return retval return False def has_privileges(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be checked on object_type object_name Name of the object on which the check is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to check, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the grant option check is performed prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if object_type != 'group': owner = _get_object_owner(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if owner is not None and name == owner: return True _privileges = privileges_list(object_name, object_type, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas) if name in _privileges: if object_type == 'group': if grant_option: retval = _privileges[name] else: retval = True return retval else: _perms = _PRIVILEGE_TYPE_MAP[object_type] if grant_option: perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms) retval = perms == _privileges[name] else: perms = [_PRIVILEGES_MAP[perm] for perm in _perms] if 'ALL' in _privs: retval = sorted(perms) == sorted(_privileges[name].keys()) else: retval = set(_privs).issubset( set(_privileges[name].keys())) return retval return False def default_privileges_grant(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Grant default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which default privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the default privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, pdefrivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = ' ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence', 'function') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = ' ALTER DEFAULT PRIVILEGES IN SCHEMA {2} GRANT {0} ON {1}S TO "{3}"'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def default_privileges_revoke(name, object_name, object_type, defprivileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019.0.0 Revoke default privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.default_privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose default privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - TRIGGER - SELECT - USAGE - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, defprivileges, _defprivs = _mod_defpriv_opts(object_type, defprivileges) _validate_default_privileges(object_type, _defprivs, defprivileges) if not has_default_privileges(name, object_name, object_type, defprivileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have default privileges: %s set', object_name, object_type, defprivileges) return False _grants = ','.join(_defprivs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'ALTER DEFAULT PRIVILEGES REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'ALTER DEFAULT PRIVILEGES IN SCHEMA {2} REVOKE {0} ON {1}S FROM {3}'.format( _grants, object_type.upper(), prepend, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Grant privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_grant user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role to which privileges should be granted object_name Name of the object on which the grant is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to grant, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL grant_option If grant_option is set to True, the recipient of the privilege can in turn grant it to others prepend Table and Sequence object types live under a schema so this should be provided if the object is not under the default `public` schema maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s already has privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}."{1}"'.format(prepend, object_name) elif object_type == 'function': on_part = '{0}'.format(object_name) else: on_part = '"{0}"'.format(object_name) if grant_option: if object_type == 'group': query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format( object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \ '"{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format( _grants, object_type.upper(), on_part, name) else: if object_type == 'group': query = 'GRANT {0} TO "{1}"'.format(object_name, name) elif (object_type in ('table', 'sequence') and object_name.upper() == 'ALL'): query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format( _grants, object_type.upper(), prepend, name) else: query = 'GRANT {0} ON {1} {2} TO "{3}"'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def privileges_revoke(name, object_name, object_type, privileges=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Revoke privileges on a postgres object CLI Example: .. code-block:: bash salt '*' postgres.privileges_revoke user_name table_name table \\ SELECT,UPDATE maintenance_db=db_name name Name of the role whose privileges should be revoked object_name Name of the object on which the revoke is to be performed object_type The object type, which can be one of the following: - table - sequence - schema - tablespace - language - database - group - function privileges Comma separated list of privileges to revoke, from the list below: - INSERT - CREATE - TRUNCATE - CONNECT - TRIGGER - SELECT - USAGE - TEMPORARY - UPDATE - EXECUTE - REFERENCES - DELETE - ALL maintenance_db The database to connect to user database username if different from config or default password user password if any password for a specified user host Database host if different from config or default port Database port if different from config or default runas System user all operations should be performed on behalf of ''' object_type, privileges, _privs = _mod_priv_opts(object_type, privileges) _validate_privileges(object_type, _privs, privileges) if not has_privileges(name, object_name, object_type, privileges, prepend=prepend, maintenance_db=maintenance_db, user=user, host=host, port=port, password=password, runas=runas): log.info('The object: %s of type: %s does not' ' have privileges: %s set', object_name, object_type, privileges) return False _grants = ','.join(_privs) if object_type in ['table', 'sequence']: on_part = '{0}.{1}'.format(prepend, object_name) else: on_part = object_name if object_type == 'group': query = 'REVOKE {0} FROM {1}'.format(object_name, name) else: query = 'REVOKE {0} ON {1} {2} FROM {3}'.format( _grants, object_type.upper(), on_part, name) ret = _psql_prepare_and_run(['-c', query], user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return ret['retcode'] == 0 def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-block:: bash salt '*' postgres.datadir_init '/var/lib/pgsql/data' name The name of the directory to initialize auth The default authentication method for local connections password The password to set for the postgres user user The database superuser name encoding The default encoding for new databases locale The default locale for new databases waldir The transaction log (WAL) directory (default is to keep WAL inside the data directory) .. versionadded:: 2019.2.0 checksums If True, the cluster will be created with data page checksums. .. note:: Data page checksums are supported since PostgreSQL 9.3. .. versionadded:: 2019.2.0 runas The system user the operation should be performed on behalf of ''' if datadir_exists(name): log.info('%s already exists', name) return False ret = _run_initdb( name, auth=auth, user=user, password=password, encoding=encoding, locale=locale, runas=runas) return ret['retcode'] == 0
saltstack/salt
salt/modules/eselect.py
exec_action
python
def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False): ''' Execute an arbitrary action on a module. module name of the module to be executed action name of the module's action to be run module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action state_only don't return any output but only the success/failure of the operation CLI Example (updating the ``php`` implementation used for ``apache2``): .. code-block:: bash salt '*' eselect.exec_action php update action_parameter='apache2' ''' out = __salt__['cmd.run']( 'eselect --brief --colour=no {0} {1} {2} {3}'.format( module, module_parameter or '', action, action_parameter or ''), python_shell=False ) out = out.strip().split('\n') if out[0].startswith('!!! Error'): return False if state_only: return True if not out: return False if len(out) == 1 and not out[0].strip(): return False return out
Execute an arbitrary action on a module. module name of the module to be executed action name of the module's action to be run module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action state_only don't return any output but only the success/failure of the operation CLI Example (updating the ``php`` implementation used for ``apache2``): .. code-block:: bash salt '*' eselect.exec_action php update action_parameter='apache2'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/eselect.py#L25-L69
null
# -*- coding: utf-8 -*- ''' Support for eselect, Gentoo's configuration and management tool. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): ''' Only work on Gentoo systems with eselect installed ''' if __grains__['os_family'] == 'Gentoo' and salt.utils.path.which('eselect'): return 'eselect' return (False, 'The eselect execution module cannot be loaded: either the system is not Gentoo or the eselect binary is not in the path.') def get_modules(): ''' List available ``eselect`` modules. CLI Example: .. code-block:: bash salt '*' eselect.get_modules ''' modules = [] module_list = exec_action('modules', 'list', action_parameter='--only-names') if not module_list: return None for module in module_list: if module not in ['help', 'usage', 'version']: modules.append(module) return modules def get_target_list(module, action_parameter=None): ''' List available targets for the given module. module name of the module to be queried for its targets action_parameter additional params passed to the defined action .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' eselect.get_target_list kernel ''' exec_output = exec_action(module, 'list', action_parameter=action_parameter) if not exec_output: return None target_list = [] if isinstance(exec_output, list): for item in exec_output: target_list.append(item.split(None, 1)[0]) return target_list return None def get_current_target(module, module_parameter=None, action_parameter=None): ''' Get the currently selected target for the given module. module name of the module to be queried for its current target module_parameter additional params passed to the defined module action_parameter additional params passed to the 'show' action CLI Example (current target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.get_current_target java-vm action_parameter='system' CLI Example (current target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.get_current_target kernel ''' result = exec_action(module, 'show', module_parameter=module_parameter, action_parameter=action_parameter)[0] if not result: return None if result == '(unset)': return None return result def set_target(module, target, module_parameter=None, action_parameter=None): ''' Set the target for the given module. Target can be specified by index or name. module name of the module for which a target should be set target name of the target to be set for this module module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action CLI Example (setting target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.set_target java-vm icedtea-bin-7 action_parameter='system' CLI Example (setting target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.set_target kernel linux-3.17.5-gentoo ''' if action_parameter: action_parameter = '{0} {1}'.format(action_parameter, target) else: action_parameter = target # get list of available modules if module not in get_modules(): log.error('Module %s not available', module) return False exec_result = exec_action(module, 'set', module_parameter=module_parameter, action_parameter=action_parameter, state_only=True) if exec_result: return exec_result return False
saltstack/salt
salt/modules/eselect.py
get_modules
python
def get_modules(): ''' List available ``eselect`` modules. CLI Example: .. code-block:: bash salt '*' eselect.get_modules ''' modules = [] module_list = exec_action('modules', 'list', action_parameter='--only-names') if not module_list: return None for module in module_list: if module not in ['help', 'usage', 'version']: modules.append(module) return modules
List available ``eselect`` modules. CLI Example: .. code-block:: bash salt '*' eselect.get_modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/eselect.py#L72-L90
[ "def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False):\n '''\n Execute an arbitrary action on a module.\n\n module\n name of the module to be executed\n\n action\n name of the module's action to be run\n\n module_parameter\n additional params passed to the defined module\n\n action_parameter\n additional params passed to the defined action\n\n state_only\n don't return any output but only the success/failure of the operation\n\n CLI Example (updating the ``php`` implementation used for ``apache2``):\n\n .. code-block:: bash\n\n salt '*' eselect.exec_action php update action_parameter='apache2'\n '''\n out = __salt__['cmd.run'](\n 'eselect --brief --colour=no {0} {1} {2} {3}'.format(\n module, module_parameter or '', action, action_parameter or ''),\n python_shell=False\n )\n out = out.strip().split('\\n')\n\n if out[0].startswith('!!! Error'):\n return False\n\n if state_only:\n return True\n\n if not out:\n return False\n\n if len(out) == 1 and not out[0].strip():\n return False\n\n return out\n" ]
# -*- coding: utf-8 -*- ''' Support for eselect, Gentoo's configuration and management tool. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): ''' Only work on Gentoo systems with eselect installed ''' if __grains__['os_family'] == 'Gentoo' and salt.utils.path.which('eselect'): return 'eselect' return (False, 'The eselect execution module cannot be loaded: either the system is not Gentoo or the eselect binary is not in the path.') def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False): ''' Execute an arbitrary action on a module. module name of the module to be executed action name of the module's action to be run module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action state_only don't return any output but only the success/failure of the operation CLI Example (updating the ``php`` implementation used for ``apache2``): .. code-block:: bash salt '*' eselect.exec_action php update action_parameter='apache2' ''' out = __salt__['cmd.run']( 'eselect --brief --colour=no {0} {1} {2} {3}'.format( module, module_parameter or '', action, action_parameter or ''), python_shell=False ) out = out.strip().split('\n') if out[0].startswith('!!! Error'): return False if state_only: return True if not out: return False if len(out) == 1 and not out[0].strip(): return False return out def get_target_list(module, action_parameter=None): ''' List available targets for the given module. module name of the module to be queried for its targets action_parameter additional params passed to the defined action .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' eselect.get_target_list kernel ''' exec_output = exec_action(module, 'list', action_parameter=action_parameter) if not exec_output: return None target_list = [] if isinstance(exec_output, list): for item in exec_output: target_list.append(item.split(None, 1)[0]) return target_list return None def get_current_target(module, module_parameter=None, action_parameter=None): ''' Get the currently selected target for the given module. module name of the module to be queried for its current target module_parameter additional params passed to the defined module action_parameter additional params passed to the 'show' action CLI Example (current target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.get_current_target java-vm action_parameter='system' CLI Example (current target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.get_current_target kernel ''' result = exec_action(module, 'show', module_parameter=module_parameter, action_parameter=action_parameter)[0] if not result: return None if result == '(unset)': return None return result def set_target(module, target, module_parameter=None, action_parameter=None): ''' Set the target for the given module. Target can be specified by index or name. module name of the module for which a target should be set target name of the target to be set for this module module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action CLI Example (setting target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.set_target java-vm icedtea-bin-7 action_parameter='system' CLI Example (setting target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.set_target kernel linux-3.17.5-gentoo ''' if action_parameter: action_parameter = '{0} {1}'.format(action_parameter, target) else: action_parameter = target # get list of available modules if module not in get_modules(): log.error('Module %s not available', module) return False exec_result = exec_action(module, 'set', module_parameter=module_parameter, action_parameter=action_parameter, state_only=True) if exec_result: return exec_result return False
saltstack/salt
salt/modules/eselect.py
get_target_list
python
def get_target_list(module, action_parameter=None): ''' List available targets for the given module. module name of the module to be queried for its targets action_parameter additional params passed to the defined action .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' eselect.get_target_list kernel ''' exec_output = exec_action(module, 'list', action_parameter=action_parameter) if not exec_output: return None target_list = [] if isinstance(exec_output, list): for item in exec_output: target_list.append(item.split(None, 1)[0]) return target_list return None
List available targets for the given module. module name of the module to be queried for its targets action_parameter additional params passed to the defined action .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' eselect.get_target_list kernel
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/eselect.py#L93-L121
[ "def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False):\n '''\n Execute an arbitrary action on a module.\n\n module\n name of the module to be executed\n\n action\n name of the module's action to be run\n\n module_parameter\n additional params passed to the defined module\n\n action_parameter\n additional params passed to the defined action\n\n state_only\n don't return any output but only the success/failure of the operation\n\n CLI Example (updating the ``php`` implementation used for ``apache2``):\n\n .. code-block:: bash\n\n salt '*' eselect.exec_action php update action_parameter='apache2'\n '''\n out = __salt__['cmd.run'](\n 'eselect --brief --colour=no {0} {1} {2} {3}'.format(\n module, module_parameter or '', action, action_parameter or ''),\n python_shell=False\n )\n out = out.strip().split('\\n')\n\n if out[0].startswith('!!! Error'):\n return False\n\n if state_only:\n return True\n\n if not out:\n return False\n\n if len(out) == 1 and not out[0].strip():\n return False\n\n return out\n" ]
# -*- coding: utf-8 -*- ''' Support for eselect, Gentoo's configuration and management tool. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): ''' Only work on Gentoo systems with eselect installed ''' if __grains__['os_family'] == 'Gentoo' and salt.utils.path.which('eselect'): return 'eselect' return (False, 'The eselect execution module cannot be loaded: either the system is not Gentoo or the eselect binary is not in the path.') def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False): ''' Execute an arbitrary action on a module. module name of the module to be executed action name of the module's action to be run module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action state_only don't return any output but only the success/failure of the operation CLI Example (updating the ``php`` implementation used for ``apache2``): .. code-block:: bash salt '*' eselect.exec_action php update action_parameter='apache2' ''' out = __salt__['cmd.run']( 'eselect --brief --colour=no {0} {1} {2} {3}'.format( module, module_parameter or '', action, action_parameter or ''), python_shell=False ) out = out.strip().split('\n') if out[0].startswith('!!! Error'): return False if state_only: return True if not out: return False if len(out) == 1 and not out[0].strip(): return False return out def get_modules(): ''' List available ``eselect`` modules. CLI Example: .. code-block:: bash salt '*' eselect.get_modules ''' modules = [] module_list = exec_action('modules', 'list', action_parameter='--only-names') if not module_list: return None for module in module_list: if module not in ['help', 'usage', 'version']: modules.append(module) return modules def get_current_target(module, module_parameter=None, action_parameter=None): ''' Get the currently selected target for the given module. module name of the module to be queried for its current target module_parameter additional params passed to the defined module action_parameter additional params passed to the 'show' action CLI Example (current target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.get_current_target java-vm action_parameter='system' CLI Example (current target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.get_current_target kernel ''' result = exec_action(module, 'show', module_parameter=module_parameter, action_parameter=action_parameter)[0] if not result: return None if result == '(unset)': return None return result def set_target(module, target, module_parameter=None, action_parameter=None): ''' Set the target for the given module. Target can be specified by index or name. module name of the module for which a target should be set target name of the target to be set for this module module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action CLI Example (setting target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.set_target java-vm icedtea-bin-7 action_parameter='system' CLI Example (setting target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.set_target kernel linux-3.17.5-gentoo ''' if action_parameter: action_parameter = '{0} {1}'.format(action_parameter, target) else: action_parameter = target # get list of available modules if module not in get_modules(): log.error('Module %s not available', module) return False exec_result = exec_action(module, 'set', module_parameter=module_parameter, action_parameter=action_parameter, state_only=True) if exec_result: return exec_result return False
saltstack/salt
salt/modules/eselect.py
get_current_target
python
def get_current_target(module, module_parameter=None, action_parameter=None): ''' Get the currently selected target for the given module. module name of the module to be queried for its current target module_parameter additional params passed to the defined module action_parameter additional params passed to the 'show' action CLI Example (current target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.get_current_target java-vm action_parameter='system' CLI Example (current target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.get_current_target kernel ''' result = exec_action(module, 'show', module_parameter=module_parameter, action_parameter=action_parameter)[0] if not result: return None if result == '(unset)': return None return result
Get the currently selected target for the given module. module name of the module to be queried for its current target module_parameter additional params passed to the defined module action_parameter additional params passed to the 'show' action CLI Example (current target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.get_current_target java-vm action_parameter='system' CLI Example (current target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.get_current_target kernel
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/eselect.py#L124-L156
[ "def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False):\n '''\n Execute an arbitrary action on a module.\n\n module\n name of the module to be executed\n\n action\n name of the module's action to be run\n\n module_parameter\n additional params passed to the defined module\n\n action_parameter\n additional params passed to the defined action\n\n state_only\n don't return any output but only the success/failure of the operation\n\n CLI Example (updating the ``php`` implementation used for ``apache2``):\n\n .. code-block:: bash\n\n salt '*' eselect.exec_action php update action_parameter='apache2'\n '''\n out = __salt__['cmd.run'](\n 'eselect --brief --colour=no {0} {1} {2} {3}'.format(\n module, module_parameter or '', action, action_parameter or ''),\n python_shell=False\n )\n out = out.strip().split('\\n')\n\n if out[0].startswith('!!! Error'):\n return False\n\n if state_only:\n return True\n\n if not out:\n return False\n\n if len(out) == 1 and not out[0].strip():\n return False\n\n return out\n" ]
# -*- coding: utf-8 -*- ''' Support for eselect, Gentoo's configuration and management tool. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): ''' Only work on Gentoo systems with eselect installed ''' if __grains__['os_family'] == 'Gentoo' and salt.utils.path.which('eselect'): return 'eselect' return (False, 'The eselect execution module cannot be loaded: either the system is not Gentoo or the eselect binary is not in the path.') def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False): ''' Execute an arbitrary action on a module. module name of the module to be executed action name of the module's action to be run module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action state_only don't return any output but only the success/failure of the operation CLI Example (updating the ``php`` implementation used for ``apache2``): .. code-block:: bash salt '*' eselect.exec_action php update action_parameter='apache2' ''' out = __salt__['cmd.run']( 'eselect --brief --colour=no {0} {1} {2} {3}'.format( module, module_parameter or '', action, action_parameter or ''), python_shell=False ) out = out.strip().split('\n') if out[0].startswith('!!! Error'): return False if state_only: return True if not out: return False if len(out) == 1 and not out[0].strip(): return False return out def get_modules(): ''' List available ``eselect`` modules. CLI Example: .. code-block:: bash salt '*' eselect.get_modules ''' modules = [] module_list = exec_action('modules', 'list', action_parameter='--only-names') if not module_list: return None for module in module_list: if module not in ['help', 'usage', 'version']: modules.append(module) return modules def get_target_list(module, action_parameter=None): ''' List available targets for the given module. module name of the module to be queried for its targets action_parameter additional params passed to the defined action .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' eselect.get_target_list kernel ''' exec_output = exec_action(module, 'list', action_parameter=action_parameter) if not exec_output: return None target_list = [] if isinstance(exec_output, list): for item in exec_output: target_list.append(item.split(None, 1)[0]) return target_list return None def set_target(module, target, module_parameter=None, action_parameter=None): ''' Set the target for the given module. Target can be specified by index or name. module name of the module for which a target should be set target name of the target to be set for this module module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action CLI Example (setting target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.set_target java-vm icedtea-bin-7 action_parameter='system' CLI Example (setting target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.set_target kernel linux-3.17.5-gentoo ''' if action_parameter: action_parameter = '{0} {1}'.format(action_parameter, target) else: action_parameter = target # get list of available modules if module not in get_modules(): log.error('Module %s not available', module) return False exec_result = exec_action(module, 'set', module_parameter=module_parameter, action_parameter=action_parameter, state_only=True) if exec_result: return exec_result return False
saltstack/salt
salt/modules/eselect.py
set_target
python
def set_target(module, target, module_parameter=None, action_parameter=None): ''' Set the target for the given module. Target can be specified by index or name. module name of the module for which a target should be set target name of the target to be set for this module module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action CLI Example (setting target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.set_target java-vm icedtea-bin-7 action_parameter='system' CLI Example (setting target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.set_target kernel linux-3.17.5-gentoo ''' if action_parameter: action_parameter = '{0} {1}'.format(action_parameter, target) else: action_parameter = target # get list of available modules if module not in get_modules(): log.error('Module %s not available', module) return False exec_result = exec_action(module, 'set', module_parameter=module_parameter, action_parameter=action_parameter, state_only=True) if exec_result: return exec_result return False
Set the target for the given module. Target can be specified by index or name. module name of the module for which a target should be set target name of the target to be set for this module module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action CLI Example (setting target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.set_target java-vm icedtea-bin-7 action_parameter='system' CLI Example (setting target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.set_target kernel linux-3.17.5-gentoo
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/eselect.py#L159-L201
[ "def get_modules():\n '''\n List available ``eselect`` modules.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' eselect.get_modules\n '''\n modules = []\n module_list = exec_action('modules', 'list', action_parameter='--only-names')\n if not module_list:\n return None\n\n for module in module_list:\n if module not in ['help', 'usage', 'version']:\n modules.append(module)\n return modules\n", "def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False):\n '''\n Execute an arbitrary action on a module.\n\n module\n name of the module to be executed\n\n action\n name of the module's action to be run\n\n module_parameter\n additional params passed to the defined module\n\n action_parameter\n additional params passed to the defined action\n\n state_only\n don't return any output but only the success/failure of the operation\n\n CLI Example (updating the ``php`` implementation used for ``apache2``):\n\n .. code-block:: bash\n\n salt '*' eselect.exec_action php update action_parameter='apache2'\n '''\n out = __salt__['cmd.run'](\n 'eselect --brief --colour=no {0} {1} {2} {3}'.format(\n module, module_parameter or '', action, action_parameter or ''),\n python_shell=False\n )\n out = out.strip().split('\\n')\n\n if out[0].startswith('!!! Error'):\n return False\n\n if state_only:\n return True\n\n if not out:\n return False\n\n if len(out) == 1 and not out[0].strip():\n return False\n\n return out\n" ]
# -*- coding: utf-8 -*- ''' Support for eselect, Gentoo's configuration and management tool. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.utils.path log = logging.getLogger(__name__) def __virtual__(): ''' Only work on Gentoo systems with eselect installed ''' if __grains__['os_family'] == 'Gentoo' and salt.utils.path.which('eselect'): return 'eselect' return (False, 'The eselect execution module cannot be loaded: either the system is not Gentoo or the eselect binary is not in the path.') def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False): ''' Execute an arbitrary action on a module. module name of the module to be executed action name of the module's action to be run module_parameter additional params passed to the defined module action_parameter additional params passed to the defined action state_only don't return any output but only the success/failure of the operation CLI Example (updating the ``php`` implementation used for ``apache2``): .. code-block:: bash salt '*' eselect.exec_action php update action_parameter='apache2' ''' out = __salt__['cmd.run']( 'eselect --brief --colour=no {0} {1} {2} {3}'.format( module, module_parameter or '', action, action_parameter or ''), python_shell=False ) out = out.strip().split('\n') if out[0].startswith('!!! Error'): return False if state_only: return True if not out: return False if len(out) == 1 and not out[0].strip(): return False return out def get_modules(): ''' List available ``eselect`` modules. CLI Example: .. code-block:: bash salt '*' eselect.get_modules ''' modules = [] module_list = exec_action('modules', 'list', action_parameter='--only-names') if not module_list: return None for module in module_list: if module not in ['help', 'usage', 'version']: modules.append(module) return modules def get_target_list(module, action_parameter=None): ''' List available targets for the given module. module name of the module to be queried for its targets action_parameter additional params passed to the defined action .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' eselect.get_target_list kernel ''' exec_output = exec_action(module, 'list', action_parameter=action_parameter) if not exec_output: return None target_list = [] if isinstance(exec_output, list): for item in exec_output: target_list.append(item.split(None, 1)[0]) return target_list return None def get_current_target(module, module_parameter=None, action_parameter=None): ''' Get the currently selected target for the given module. module name of the module to be queried for its current target module_parameter additional params passed to the defined module action_parameter additional params passed to the 'show' action CLI Example (current target of system-wide ``java-vm``): .. code-block:: bash salt '*' eselect.get_current_target java-vm action_parameter='system' CLI Example (current target of ``kernel`` symlink): .. code-block:: bash salt '*' eselect.get_current_target kernel ''' result = exec_action(module, 'show', module_parameter=module_parameter, action_parameter=action_parameter)[0] if not result: return None if result == '(unset)': return None return result
saltstack/salt
salt/thorium/calc.py
calc
python
def calc(name, num, oper, minimum=0, maximum=0, ref=None): ''' Perform a calculation on the ``num`` most recent values. Requires a list. Valid values for ``oper`` are: - add: Add last ``num`` values together - mul: Multiple last ``num`` values together - mean: Calculate mean of last ``num`` values - median: Calculate median of last ``num`` values - median_low: Calculate low median of last ``num`` values - median_high: Calculate high median of last ``num`` values - median_grouped: Calculate grouped median of last ``num`` values - mode: Calculate mode of last ``num`` values USAGE: .. code-block:: yaml foo: calc.calc: - name: myregentry - num: 5 - oper: mean ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: ret['comment'] = '{0} not found in register'.format(name) ret['result'] = False def opadd(vals): sum = 0 for val in vals: sum = sum + val return sum def opmul(vals): prod = 0 for val in vals: prod = prod * val return prod ops = { 'add': opadd, 'mul': opmul, 'mean': statistics.mean, 'median': statistics.median, 'median_low': statistics.median_low, 'median_high': statistics.median_high, 'median_grouped': statistics.median_grouped, 'mode': statistics.mode, } count = 0 vals = [] __reg__[name]['val'].reverse() for regitem in __reg__[name]['val']: count += 1 if count > num: break if ref is None: vals.append(regitem) else: vals.append(regitem[ref]) answer = ops[oper](vals) if minimum > 0 and answer < minimum: ret['result'] = False if 0 < maximum < answer: ret['result'] = False ret['changes'] = { 'Number of values': len(vals), 'Operator': oper, 'Answer': answer, } return ret
Perform a calculation on the ``num`` most recent values. Requires a list. Valid values for ``oper`` are: - add: Add last ``num`` values together - mul: Multiple last ``num`` values together - mean: Calculate mean of last ``num`` values - median: Calculate median of last ``num`` values - median_low: Calculate low median of last ``num`` values - median_high: Calculate high median of last ``num`` values - median_grouped: Calculate grouped median of last ``num`` values - mode: Calculate mode of last ``num`` values USAGE: .. code-block:: yaml foo: calc.calc: - name: myregentry - num: 5 - oper: mean
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L28-L108
null
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. .. versionadded:: 2016.11.0 :depends: statistics PyPi module ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals try: import statistics HAS_STATS = True except ImportError: HAS_STATS = False def __virtual__(): ''' The statistics module must be pip installed ''' return HAS_STATS def add(name, num, minimum=0, maximum=0, ref=None): ''' Adds together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.add: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='add', minimum=minimum, maximum=maximum, ref=ref ) def mul(name, num, minimum=0, maximum=0, ref=None): ''' Multiplies together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mul: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mul', minimum=minimum, maximum=maximum, ref=ref ) def mean(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mean: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mean', minimum=minimum, maximum=maximum, ref=ref ) def median(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median', minimum=minimum, maximum=maximum, ref=ref ) def median_low(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_low', minimum=minimum, maximum=maximum, ref=ref ) def median_high(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the high mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_high: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_high', minimum=minimum, maximum=maximum, ref=ref ) def median_grouped(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the grouped mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_grouped: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_grouped', minimum=minimum, maximum=maximum, ref=ref ) def mode(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mode of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mode: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mode', minimum=minimum, maximum=maximum, ref=ref )
saltstack/salt
salt/thorium/calc.py
add
python
def add(name, num, minimum=0, maximum=0, ref=None): ''' Adds together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.add: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='add', minimum=minimum, maximum=maximum, ref=ref )
Adds together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.add: - name: myregentry - num: 5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L111-L131
[ "def calc(name, num, oper, minimum=0, maximum=0, ref=None):\n '''\n Perform a calculation on the ``num`` most recent values. Requires a list.\n Valid values for ``oper`` are:\n\n - add: Add last ``num`` values together\n - mul: Multiple last ``num`` values together\n - mean: Calculate mean of last ``num`` values\n - median: Calculate median of last ``num`` values\n - median_low: Calculate low median of last ``num`` values\n - median_high: Calculate high median of last ``num`` values\n - median_grouped: Calculate grouped median of last ``num`` values\n - mode: Calculate mode of last ``num`` values\n\n USAGE:\n\n .. code-block:: yaml\n\n foo:\n calc.calc:\n - name: myregentry\n - num: 5\n - oper: mean\n '''\n ret = {'name': name,\n 'changes': {},\n 'comment': '',\n 'result': True}\n if name not in __reg__:\n ret['comment'] = '{0} not found in register'.format(name)\n ret['result'] = False\n\n def opadd(vals):\n sum = 0\n for val in vals:\n sum = sum + val\n return sum\n\n def opmul(vals):\n prod = 0\n for val in vals:\n prod = prod * val\n return prod\n\n ops = {\n 'add': opadd,\n 'mul': opmul,\n 'mean': statistics.mean,\n 'median': statistics.median,\n 'median_low': statistics.median_low,\n 'median_high': statistics.median_high,\n 'median_grouped': statistics.median_grouped,\n 'mode': statistics.mode,\n }\n\n count = 0\n vals = []\n __reg__[name]['val'].reverse()\n for regitem in __reg__[name]['val']:\n count += 1\n if count > num:\n break\n if ref is None:\n vals.append(regitem)\n else:\n vals.append(regitem[ref])\n\n answer = ops[oper](vals)\n\n if minimum > 0 and answer < minimum:\n ret['result'] = False\n\n if 0 < maximum < answer:\n ret['result'] = False\n\n ret['changes'] = {\n 'Number of values': len(vals),\n 'Operator': oper,\n 'Answer': answer,\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. .. versionadded:: 2016.11.0 :depends: statistics PyPi module ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals try: import statistics HAS_STATS = True except ImportError: HAS_STATS = False def __virtual__(): ''' The statistics module must be pip installed ''' return HAS_STATS def calc(name, num, oper, minimum=0, maximum=0, ref=None): ''' Perform a calculation on the ``num`` most recent values. Requires a list. Valid values for ``oper`` are: - add: Add last ``num`` values together - mul: Multiple last ``num`` values together - mean: Calculate mean of last ``num`` values - median: Calculate median of last ``num`` values - median_low: Calculate low median of last ``num`` values - median_high: Calculate high median of last ``num`` values - median_grouped: Calculate grouped median of last ``num`` values - mode: Calculate mode of last ``num`` values USAGE: .. code-block:: yaml foo: calc.calc: - name: myregentry - num: 5 - oper: mean ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: ret['comment'] = '{0} not found in register'.format(name) ret['result'] = False def opadd(vals): sum = 0 for val in vals: sum = sum + val return sum def opmul(vals): prod = 0 for val in vals: prod = prod * val return prod ops = { 'add': opadd, 'mul': opmul, 'mean': statistics.mean, 'median': statistics.median, 'median_low': statistics.median_low, 'median_high': statistics.median_high, 'median_grouped': statistics.median_grouped, 'mode': statistics.mode, } count = 0 vals = [] __reg__[name]['val'].reverse() for regitem in __reg__[name]['val']: count += 1 if count > num: break if ref is None: vals.append(regitem) else: vals.append(regitem[ref]) answer = ops[oper](vals) if minimum > 0 and answer < minimum: ret['result'] = False if 0 < maximum < answer: ret['result'] = False ret['changes'] = { 'Number of values': len(vals), 'Operator': oper, 'Answer': answer, } return ret def mul(name, num, minimum=0, maximum=0, ref=None): ''' Multiplies together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mul: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mul', minimum=minimum, maximum=maximum, ref=ref ) def mean(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mean: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mean', minimum=minimum, maximum=maximum, ref=ref ) def median(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median', minimum=minimum, maximum=maximum, ref=ref ) def median_low(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_low', minimum=minimum, maximum=maximum, ref=ref ) def median_high(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the high mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_high: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_high', minimum=minimum, maximum=maximum, ref=ref ) def median_grouped(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the grouped mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_grouped: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_grouped', minimum=minimum, maximum=maximum, ref=ref ) def mode(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mode of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mode: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mode', minimum=minimum, maximum=maximum, ref=ref )
saltstack/salt
salt/thorium/calc.py
mul
python
def mul(name, num, minimum=0, maximum=0, ref=None): ''' Multiplies together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mul: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mul', minimum=minimum, maximum=maximum, ref=ref )
Multiplies together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mul: - name: myregentry - num: 5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L134-L154
[ "def calc(name, num, oper, minimum=0, maximum=0, ref=None):\n '''\n Perform a calculation on the ``num`` most recent values. Requires a list.\n Valid values for ``oper`` are:\n\n - add: Add last ``num`` values together\n - mul: Multiple last ``num`` values together\n - mean: Calculate mean of last ``num`` values\n - median: Calculate median of last ``num`` values\n - median_low: Calculate low median of last ``num`` values\n - median_high: Calculate high median of last ``num`` values\n - median_grouped: Calculate grouped median of last ``num`` values\n - mode: Calculate mode of last ``num`` values\n\n USAGE:\n\n .. code-block:: yaml\n\n foo:\n calc.calc:\n - name: myregentry\n - num: 5\n - oper: mean\n '''\n ret = {'name': name,\n 'changes': {},\n 'comment': '',\n 'result': True}\n if name not in __reg__:\n ret['comment'] = '{0} not found in register'.format(name)\n ret['result'] = False\n\n def opadd(vals):\n sum = 0\n for val in vals:\n sum = sum + val\n return sum\n\n def opmul(vals):\n prod = 0\n for val in vals:\n prod = prod * val\n return prod\n\n ops = {\n 'add': opadd,\n 'mul': opmul,\n 'mean': statistics.mean,\n 'median': statistics.median,\n 'median_low': statistics.median_low,\n 'median_high': statistics.median_high,\n 'median_grouped': statistics.median_grouped,\n 'mode': statistics.mode,\n }\n\n count = 0\n vals = []\n __reg__[name]['val'].reverse()\n for regitem in __reg__[name]['val']:\n count += 1\n if count > num:\n break\n if ref is None:\n vals.append(regitem)\n else:\n vals.append(regitem[ref])\n\n answer = ops[oper](vals)\n\n if minimum > 0 and answer < minimum:\n ret['result'] = False\n\n if 0 < maximum < answer:\n ret['result'] = False\n\n ret['changes'] = {\n 'Number of values': len(vals),\n 'Operator': oper,\n 'Answer': answer,\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. .. versionadded:: 2016.11.0 :depends: statistics PyPi module ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals try: import statistics HAS_STATS = True except ImportError: HAS_STATS = False def __virtual__(): ''' The statistics module must be pip installed ''' return HAS_STATS def calc(name, num, oper, minimum=0, maximum=0, ref=None): ''' Perform a calculation on the ``num`` most recent values. Requires a list. Valid values for ``oper`` are: - add: Add last ``num`` values together - mul: Multiple last ``num`` values together - mean: Calculate mean of last ``num`` values - median: Calculate median of last ``num`` values - median_low: Calculate low median of last ``num`` values - median_high: Calculate high median of last ``num`` values - median_grouped: Calculate grouped median of last ``num`` values - mode: Calculate mode of last ``num`` values USAGE: .. code-block:: yaml foo: calc.calc: - name: myregentry - num: 5 - oper: mean ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: ret['comment'] = '{0} not found in register'.format(name) ret['result'] = False def opadd(vals): sum = 0 for val in vals: sum = sum + val return sum def opmul(vals): prod = 0 for val in vals: prod = prod * val return prod ops = { 'add': opadd, 'mul': opmul, 'mean': statistics.mean, 'median': statistics.median, 'median_low': statistics.median_low, 'median_high': statistics.median_high, 'median_grouped': statistics.median_grouped, 'mode': statistics.mode, } count = 0 vals = [] __reg__[name]['val'].reverse() for regitem in __reg__[name]['val']: count += 1 if count > num: break if ref is None: vals.append(regitem) else: vals.append(regitem[ref]) answer = ops[oper](vals) if minimum > 0 and answer < minimum: ret['result'] = False if 0 < maximum < answer: ret['result'] = False ret['changes'] = { 'Number of values': len(vals), 'Operator': oper, 'Answer': answer, } return ret def add(name, num, minimum=0, maximum=0, ref=None): ''' Adds together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.add: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='add', minimum=minimum, maximum=maximum, ref=ref ) def mean(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mean: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mean', minimum=minimum, maximum=maximum, ref=ref ) def median(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median', minimum=minimum, maximum=maximum, ref=ref ) def median_low(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_low', minimum=minimum, maximum=maximum, ref=ref ) def median_high(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the high mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_high: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_high', minimum=minimum, maximum=maximum, ref=ref ) def median_grouped(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the grouped mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_grouped: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_grouped', minimum=minimum, maximum=maximum, ref=ref ) def mode(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mode of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mode: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mode', minimum=minimum, maximum=maximum, ref=ref )
saltstack/salt
salt/thorium/calc.py
mean
python
def mean(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mean: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mean', minimum=minimum, maximum=maximum, ref=ref )
Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mean: - name: myregentry - num: 5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L157-L177
[ "def calc(name, num, oper, minimum=0, maximum=0, ref=None):\n '''\n Perform a calculation on the ``num`` most recent values. Requires a list.\n Valid values for ``oper`` are:\n\n - add: Add last ``num`` values together\n - mul: Multiple last ``num`` values together\n - mean: Calculate mean of last ``num`` values\n - median: Calculate median of last ``num`` values\n - median_low: Calculate low median of last ``num`` values\n - median_high: Calculate high median of last ``num`` values\n - median_grouped: Calculate grouped median of last ``num`` values\n - mode: Calculate mode of last ``num`` values\n\n USAGE:\n\n .. code-block:: yaml\n\n foo:\n calc.calc:\n - name: myregentry\n - num: 5\n - oper: mean\n '''\n ret = {'name': name,\n 'changes': {},\n 'comment': '',\n 'result': True}\n if name not in __reg__:\n ret['comment'] = '{0} not found in register'.format(name)\n ret['result'] = False\n\n def opadd(vals):\n sum = 0\n for val in vals:\n sum = sum + val\n return sum\n\n def opmul(vals):\n prod = 0\n for val in vals:\n prod = prod * val\n return prod\n\n ops = {\n 'add': opadd,\n 'mul': opmul,\n 'mean': statistics.mean,\n 'median': statistics.median,\n 'median_low': statistics.median_low,\n 'median_high': statistics.median_high,\n 'median_grouped': statistics.median_grouped,\n 'mode': statistics.mode,\n }\n\n count = 0\n vals = []\n __reg__[name]['val'].reverse()\n for regitem in __reg__[name]['val']:\n count += 1\n if count > num:\n break\n if ref is None:\n vals.append(regitem)\n else:\n vals.append(regitem[ref])\n\n answer = ops[oper](vals)\n\n if minimum > 0 and answer < minimum:\n ret['result'] = False\n\n if 0 < maximum < answer:\n ret['result'] = False\n\n ret['changes'] = {\n 'Number of values': len(vals),\n 'Operator': oper,\n 'Answer': answer,\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. .. versionadded:: 2016.11.0 :depends: statistics PyPi module ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals try: import statistics HAS_STATS = True except ImportError: HAS_STATS = False def __virtual__(): ''' The statistics module must be pip installed ''' return HAS_STATS def calc(name, num, oper, minimum=0, maximum=0, ref=None): ''' Perform a calculation on the ``num`` most recent values. Requires a list. Valid values for ``oper`` are: - add: Add last ``num`` values together - mul: Multiple last ``num`` values together - mean: Calculate mean of last ``num`` values - median: Calculate median of last ``num`` values - median_low: Calculate low median of last ``num`` values - median_high: Calculate high median of last ``num`` values - median_grouped: Calculate grouped median of last ``num`` values - mode: Calculate mode of last ``num`` values USAGE: .. code-block:: yaml foo: calc.calc: - name: myregentry - num: 5 - oper: mean ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: ret['comment'] = '{0} not found in register'.format(name) ret['result'] = False def opadd(vals): sum = 0 for val in vals: sum = sum + val return sum def opmul(vals): prod = 0 for val in vals: prod = prod * val return prod ops = { 'add': opadd, 'mul': opmul, 'mean': statistics.mean, 'median': statistics.median, 'median_low': statistics.median_low, 'median_high': statistics.median_high, 'median_grouped': statistics.median_grouped, 'mode': statistics.mode, } count = 0 vals = [] __reg__[name]['val'].reverse() for regitem in __reg__[name]['val']: count += 1 if count > num: break if ref is None: vals.append(regitem) else: vals.append(regitem[ref]) answer = ops[oper](vals) if minimum > 0 and answer < minimum: ret['result'] = False if 0 < maximum < answer: ret['result'] = False ret['changes'] = { 'Number of values': len(vals), 'Operator': oper, 'Answer': answer, } return ret def add(name, num, minimum=0, maximum=0, ref=None): ''' Adds together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.add: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='add', minimum=minimum, maximum=maximum, ref=ref ) def mul(name, num, minimum=0, maximum=0, ref=None): ''' Multiplies together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mul: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mul', minimum=minimum, maximum=maximum, ref=ref ) def median(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median', minimum=minimum, maximum=maximum, ref=ref ) def median_low(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_low', minimum=minimum, maximum=maximum, ref=ref ) def median_high(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the high mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_high: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_high', minimum=minimum, maximum=maximum, ref=ref ) def median_grouped(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the grouped mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_grouped: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_grouped', minimum=minimum, maximum=maximum, ref=ref ) def mode(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mode of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mode: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mode', minimum=minimum, maximum=maximum, ref=ref )
saltstack/salt
salt/thorium/calc.py
median
python
def median(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median', minimum=minimum, maximum=maximum, ref=ref )
Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median: - name: myregentry - num: 5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L180-L200
[ "def calc(name, num, oper, minimum=0, maximum=0, ref=None):\n '''\n Perform a calculation on the ``num`` most recent values. Requires a list.\n Valid values for ``oper`` are:\n\n - add: Add last ``num`` values together\n - mul: Multiple last ``num`` values together\n - mean: Calculate mean of last ``num`` values\n - median: Calculate median of last ``num`` values\n - median_low: Calculate low median of last ``num`` values\n - median_high: Calculate high median of last ``num`` values\n - median_grouped: Calculate grouped median of last ``num`` values\n - mode: Calculate mode of last ``num`` values\n\n USAGE:\n\n .. code-block:: yaml\n\n foo:\n calc.calc:\n - name: myregentry\n - num: 5\n - oper: mean\n '''\n ret = {'name': name,\n 'changes': {},\n 'comment': '',\n 'result': True}\n if name not in __reg__:\n ret['comment'] = '{0} not found in register'.format(name)\n ret['result'] = False\n\n def opadd(vals):\n sum = 0\n for val in vals:\n sum = sum + val\n return sum\n\n def opmul(vals):\n prod = 0\n for val in vals:\n prod = prod * val\n return prod\n\n ops = {\n 'add': opadd,\n 'mul': opmul,\n 'mean': statistics.mean,\n 'median': statistics.median,\n 'median_low': statistics.median_low,\n 'median_high': statistics.median_high,\n 'median_grouped': statistics.median_grouped,\n 'mode': statistics.mode,\n }\n\n count = 0\n vals = []\n __reg__[name]['val'].reverse()\n for regitem in __reg__[name]['val']:\n count += 1\n if count > num:\n break\n if ref is None:\n vals.append(regitem)\n else:\n vals.append(regitem[ref])\n\n answer = ops[oper](vals)\n\n if minimum > 0 and answer < minimum:\n ret['result'] = False\n\n if 0 < maximum < answer:\n ret['result'] = False\n\n ret['changes'] = {\n 'Number of values': len(vals),\n 'Operator': oper,\n 'Answer': answer,\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. .. versionadded:: 2016.11.0 :depends: statistics PyPi module ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals try: import statistics HAS_STATS = True except ImportError: HAS_STATS = False def __virtual__(): ''' The statistics module must be pip installed ''' return HAS_STATS def calc(name, num, oper, minimum=0, maximum=0, ref=None): ''' Perform a calculation on the ``num`` most recent values. Requires a list. Valid values for ``oper`` are: - add: Add last ``num`` values together - mul: Multiple last ``num`` values together - mean: Calculate mean of last ``num`` values - median: Calculate median of last ``num`` values - median_low: Calculate low median of last ``num`` values - median_high: Calculate high median of last ``num`` values - median_grouped: Calculate grouped median of last ``num`` values - mode: Calculate mode of last ``num`` values USAGE: .. code-block:: yaml foo: calc.calc: - name: myregentry - num: 5 - oper: mean ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: ret['comment'] = '{0} not found in register'.format(name) ret['result'] = False def opadd(vals): sum = 0 for val in vals: sum = sum + val return sum def opmul(vals): prod = 0 for val in vals: prod = prod * val return prod ops = { 'add': opadd, 'mul': opmul, 'mean': statistics.mean, 'median': statistics.median, 'median_low': statistics.median_low, 'median_high': statistics.median_high, 'median_grouped': statistics.median_grouped, 'mode': statistics.mode, } count = 0 vals = [] __reg__[name]['val'].reverse() for regitem in __reg__[name]['val']: count += 1 if count > num: break if ref is None: vals.append(regitem) else: vals.append(regitem[ref]) answer = ops[oper](vals) if minimum > 0 and answer < minimum: ret['result'] = False if 0 < maximum < answer: ret['result'] = False ret['changes'] = { 'Number of values': len(vals), 'Operator': oper, 'Answer': answer, } return ret def add(name, num, minimum=0, maximum=0, ref=None): ''' Adds together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.add: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='add', minimum=minimum, maximum=maximum, ref=ref ) def mul(name, num, minimum=0, maximum=0, ref=None): ''' Multiplies together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mul: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mul', minimum=minimum, maximum=maximum, ref=ref ) def mean(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mean: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mean', minimum=minimum, maximum=maximum, ref=ref ) def median_low(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_low', minimum=minimum, maximum=maximum, ref=ref ) def median_high(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the high mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_high: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_high', minimum=minimum, maximum=maximum, ref=ref ) def median_grouped(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the grouped mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_grouped: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_grouped', minimum=minimum, maximum=maximum, ref=ref ) def mode(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mode of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mode: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mode', minimum=minimum, maximum=maximum, ref=ref )
saltstack/salt
salt/thorium/calc.py
median_low
python
def median_low(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_low', minimum=minimum, maximum=maximum, ref=ref )
Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L203-L223
[ "def calc(name, num, oper, minimum=0, maximum=0, ref=None):\n '''\n Perform a calculation on the ``num`` most recent values. Requires a list.\n Valid values for ``oper`` are:\n\n - add: Add last ``num`` values together\n - mul: Multiple last ``num`` values together\n - mean: Calculate mean of last ``num`` values\n - median: Calculate median of last ``num`` values\n - median_low: Calculate low median of last ``num`` values\n - median_high: Calculate high median of last ``num`` values\n - median_grouped: Calculate grouped median of last ``num`` values\n - mode: Calculate mode of last ``num`` values\n\n USAGE:\n\n .. code-block:: yaml\n\n foo:\n calc.calc:\n - name: myregentry\n - num: 5\n - oper: mean\n '''\n ret = {'name': name,\n 'changes': {},\n 'comment': '',\n 'result': True}\n if name not in __reg__:\n ret['comment'] = '{0} not found in register'.format(name)\n ret['result'] = False\n\n def opadd(vals):\n sum = 0\n for val in vals:\n sum = sum + val\n return sum\n\n def opmul(vals):\n prod = 0\n for val in vals:\n prod = prod * val\n return prod\n\n ops = {\n 'add': opadd,\n 'mul': opmul,\n 'mean': statistics.mean,\n 'median': statistics.median,\n 'median_low': statistics.median_low,\n 'median_high': statistics.median_high,\n 'median_grouped': statistics.median_grouped,\n 'mode': statistics.mode,\n }\n\n count = 0\n vals = []\n __reg__[name]['val'].reverse()\n for regitem in __reg__[name]['val']:\n count += 1\n if count > num:\n break\n if ref is None:\n vals.append(regitem)\n else:\n vals.append(regitem[ref])\n\n answer = ops[oper](vals)\n\n if minimum > 0 and answer < minimum:\n ret['result'] = False\n\n if 0 < maximum < answer:\n ret['result'] = False\n\n ret['changes'] = {\n 'Number of values': len(vals),\n 'Operator': oper,\n 'Answer': answer,\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. .. versionadded:: 2016.11.0 :depends: statistics PyPi module ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals try: import statistics HAS_STATS = True except ImportError: HAS_STATS = False def __virtual__(): ''' The statistics module must be pip installed ''' return HAS_STATS def calc(name, num, oper, minimum=0, maximum=0, ref=None): ''' Perform a calculation on the ``num`` most recent values. Requires a list. Valid values for ``oper`` are: - add: Add last ``num`` values together - mul: Multiple last ``num`` values together - mean: Calculate mean of last ``num`` values - median: Calculate median of last ``num`` values - median_low: Calculate low median of last ``num`` values - median_high: Calculate high median of last ``num`` values - median_grouped: Calculate grouped median of last ``num`` values - mode: Calculate mode of last ``num`` values USAGE: .. code-block:: yaml foo: calc.calc: - name: myregentry - num: 5 - oper: mean ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: ret['comment'] = '{0} not found in register'.format(name) ret['result'] = False def opadd(vals): sum = 0 for val in vals: sum = sum + val return sum def opmul(vals): prod = 0 for val in vals: prod = prod * val return prod ops = { 'add': opadd, 'mul': opmul, 'mean': statistics.mean, 'median': statistics.median, 'median_low': statistics.median_low, 'median_high': statistics.median_high, 'median_grouped': statistics.median_grouped, 'mode': statistics.mode, } count = 0 vals = [] __reg__[name]['val'].reverse() for regitem in __reg__[name]['val']: count += 1 if count > num: break if ref is None: vals.append(regitem) else: vals.append(regitem[ref]) answer = ops[oper](vals) if minimum > 0 and answer < minimum: ret['result'] = False if 0 < maximum < answer: ret['result'] = False ret['changes'] = { 'Number of values': len(vals), 'Operator': oper, 'Answer': answer, } return ret def add(name, num, minimum=0, maximum=0, ref=None): ''' Adds together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.add: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='add', minimum=minimum, maximum=maximum, ref=ref ) def mul(name, num, minimum=0, maximum=0, ref=None): ''' Multiplies together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mul: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mul', minimum=minimum, maximum=maximum, ref=ref ) def mean(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mean: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mean', minimum=minimum, maximum=maximum, ref=ref ) def median(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median', minimum=minimum, maximum=maximum, ref=ref ) def median_high(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the high mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_high: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_high', minimum=minimum, maximum=maximum, ref=ref ) def median_grouped(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the grouped mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_grouped: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_grouped', minimum=minimum, maximum=maximum, ref=ref ) def mode(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mode of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mode: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mode', minimum=minimum, maximum=maximum, ref=ref )
saltstack/salt
salt/thorium/calc.py
median_high
python
def median_high(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the high mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_high: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_high', minimum=minimum, maximum=maximum, ref=ref )
Calculates the high mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_high: - name: myregentry - num: 5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L226-L246
[ "def calc(name, num, oper, minimum=0, maximum=0, ref=None):\n '''\n Perform a calculation on the ``num`` most recent values. Requires a list.\n Valid values for ``oper`` are:\n\n - add: Add last ``num`` values together\n - mul: Multiple last ``num`` values together\n - mean: Calculate mean of last ``num`` values\n - median: Calculate median of last ``num`` values\n - median_low: Calculate low median of last ``num`` values\n - median_high: Calculate high median of last ``num`` values\n - median_grouped: Calculate grouped median of last ``num`` values\n - mode: Calculate mode of last ``num`` values\n\n USAGE:\n\n .. code-block:: yaml\n\n foo:\n calc.calc:\n - name: myregentry\n - num: 5\n - oper: mean\n '''\n ret = {'name': name,\n 'changes': {},\n 'comment': '',\n 'result': True}\n if name not in __reg__:\n ret['comment'] = '{0} not found in register'.format(name)\n ret['result'] = False\n\n def opadd(vals):\n sum = 0\n for val in vals:\n sum = sum + val\n return sum\n\n def opmul(vals):\n prod = 0\n for val in vals:\n prod = prod * val\n return prod\n\n ops = {\n 'add': opadd,\n 'mul': opmul,\n 'mean': statistics.mean,\n 'median': statistics.median,\n 'median_low': statistics.median_low,\n 'median_high': statistics.median_high,\n 'median_grouped': statistics.median_grouped,\n 'mode': statistics.mode,\n }\n\n count = 0\n vals = []\n __reg__[name]['val'].reverse()\n for regitem in __reg__[name]['val']:\n count += 1\n if count > num:\n break\n if ref is None:\n vals.append(regitem)\n else:\n vals.append(regitem[ref])\n\n answer = ops[oper](vals)\n\n if minimum > 0 and answer < minimum:\n ret['result'] = False\n\n if 0 < maximum < answer:\n ret['result'] = False\n\n ret['changes'] = {\n 'Number of values': len(vals),\n 'Operator': oper,\n 'Answer': answer,\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. .. versionadded:: 2016.11.0 :depends: statistics PyPi module ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals try: import statistics HAS_STATS = True except ImportError: HAS_STATS = False def __virtual__(): ''' The statistics module must be pip installed ''' return HAS_STATS def calc(name, num, oper, minimum=0, maximum=0, ref=None): ''' Perform a calculation on the ``num`` most recent values. Requires a list. Valid values for ``oper`` are: - add: Add last ``num`` values together - mul: Multiple last ``num`` values together - mean: Calculate mean of last ``num`` values - median: Calculate median of last ``num`` values - median_low: Calculate low median of last ``num`` values - median_high: Calculate high median of last ``num`` values - median_grouped: Calculate grouped median of last ``num`` values - mode: Calculate mode of last ``num`` values USAGE: .. code-block:: yaml foo: calc.calc: - name: myregentry - num: 5 - oper: mean ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: ret['comment'] = '{0} not found in register'.format(name) ret['result'] = False def opadd(vals): sum = 0 for val in vals: sum = sum + val return sum def opmul(vals): prod = 0 for val in vals: prod = prod * val return prod ops = { 'add': opadd, 'mul': opmul, 'mean': statistics.mean, 'median': statistics.median, 'median_low': statistics.median_low, 'median_high': statistics.median_high, 'median_grouped': statistics.median_grouped, 'mode': statistics.mode, } count = 0 vals = [] __reg__[name]['val'].reverse() for regitem in __reg__[name]['val']: count += 1 if count > num: break if ref is None: vals.append(regitem) else: vals.append(regitem[ref]) answer = ops[oper](vals) if minimum > 0 and answer < minimum: ret['result'] = False if 0 < maximum < answer: ret['result'] = False ret['changes'] = { 'Number of values': len(vals), 'Operator': oper, 'Answer': answer, } return ret def add(name, num, minimum=0, maximum=0, ref=None): ''' Adds together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.add: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='add', minimum=minimum, maximum=maximum, ref=ref ) def mul(name, num, minimum=0, maximum=0, ref=None): ''' Multiplies together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mul: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mul', minimum=minimum, maximum=maximum, ref=ref ) def mean(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mean: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mean', minimum=minimum, maximum=maximum, ref=ref ) def median(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median', minimum=minimum, maximum=maximum, ref=ref ) def median_low(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_low', minimum=minimum, maximum=maximum, ref=ref ) def median_grouped(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the grouped mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_grouped: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_grouped', minimum=minimum, maximum=maximum, ref=ref ) def mode(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mode of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mode: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mode', minimum=minimum, maximum=maximum, ref=ref )
saltstack/salt
salt/thorium/calc.py
median_grouped
python
def median_grouped(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the grouped mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_grouped: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_grouped', minimum=minimum, maximum=maximum, ref=ref )
Calculates the grouped mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_grouped: - name: myregentry - num: 5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L249-L270
[ "def calc(name, num, oper, minimum=0, maximum=0, ref=None):\n '''\n Perform a calculation on the ``num`` most recent values. Requires a list.\n Valid values for ``oper`` are:\n\n - add: Add last ``num`` values together\n - mul: Multiple last ``num`` values together\n - mean: Calculate mean of last ``num`` values\n - median: Calculate median of last ``num`` values\n - median_low: Calculate low median of last ``num`` values\n - median_high: Calculate high median of last ``num`` values\n - median_grouped: Calculate grouped median of last ``num`` values\n - mode: Calculate mode of last ``num`` values\n\n USAGE:\n\n .. code-block:: yaml\n\n foo:\n calc.calc:\n - name: myregentry\n - num: 5\n - oper: mean\n '''\n ret = {'name': name,\n 'changes': {},\n 'comment': '',\n 'result': True}\n if name not in __reg__:\n ret['comment'] = '{0} not found in register'.format(name)\n ret['result'] = False\n\n def opadd(vals):\n sum = 0\n for val in vals:\n sum = sum + val\n return sum\n\n def opmul(vals):\n prod = 0\n for val in vals:\n prod = prod * val\n return prod\n\n ops = {\n 'add': opadd,\n 'mul': opmul,\n 'mean': statistics.mean,\n 'median': statistics.median,\n 'median_low': statistics.median_low,\n 'median_high': statistics.median_high,\n 'median_grouped': statistics.median_grouped,\n 'mode': statistics.mode,\n }\n\n count = 0\n vals = []\n __reg__[name]['val'].reverse()\n for regitem in __reg__[name]['val']:\n count += 1\n if count > num:\n break\n if ref is None:\n vals.append(regitem)\n else:\n vals.append(regitem[ref])\n\n answer = ops[oper](vals)\n\n if minimum > 0 and answer < minimum:\n ret['result'] = False\n\n if 0 < maximum < answer:\n ret['result'] = False\n\n ret['changes'] = {\n 'Number of values': len(vals),\n 'Operator': oper,\n 'Answer': answer,\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. .. versionadded:: 2016.11.0 :depends: statistics PyPi module ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals try: import statistics HAS_STATS = True except ImportError: HAS_STATS = False def __virtual__(): ''' The statistics module must be pip installed ''' return HAS_STATS def calc(name, num, oper, minimum=0, maximum=0, ref=None): ''' Perform a calculation on the ``num`` most recent values. Requires a list. Valid values for ``oper`` are: - add: Add last ``num`` values together - mul: Multiple last ``num`` values together - mean: Calculate mean of last ``num`` values - median: Calculate median of last ``num`` values - median_low: Calculate low median of last ``num`` values - median_high: Calculate high median of last ``num`` values - median_grouped: Calculate grouped median of last ``num`` values - mode: Calculate mode of last ``num`` values USAGE: .. code-block:: yaml foo: calc.calc: - name: myregentry - num: 5 - oper: mean ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: ret['comment'] = '{0} not found in register'.format(name) ret['result'] = False def opadd(vals): sum = 0 for val in vals: sum = sum + val return sum def opmul(vals): prod = 0 for val in vals: prod = prod * val return prod ops = { 'add': opadd, 'mul': opmul, 'mean': statistics.mean, 'median': statistics.median, 'median_low': statistics.median_low, 'median_high': statistics.median_high, 'median_grouped': statistics.median_grouped, 'mode': statistics.mode, } count = 0 vals = [] __reg__[name]['val'].reverse() for regitem in __reg__[name]['val']: count += 1 if count > num: break if ref is None: vals.append(regitem) else: vals.append(regitem[ref]) answer = ops[oper](vals) if minimum > 0 and answer < minimum: ret['result'] = False if 0 < maximum < answer: ret['result'] = False ret['changes'] = { 'Number of values': len(vals), 'Operator': oper, 'Answer': answer, } return ret def add(name, num, minimum=0, maximum=0, ref=None): ''' Adds together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.add: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='add', minimum=minimum, maximum=maximum, ref=ref ) def mul(name, num, minimum=0, maximum=0, ref=None): ''' Multiplies together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mul: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mul', minimum=minimum, maximum=maximum, ref=ref ) def mean(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mean: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mean', minimum=minimum, maximum=maximum, ref=ref ) def median(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median', minimum=minimum, maximum=maximum, ref=ref ) def median_low(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_low', minimum=minimum, maximum=maximum, ref=ref ) def median_high(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the high mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_high: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_high', minimum=minimum, maximum=maximum, ref=ref ) def mode(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mode of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mode: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mode', minimum=minimum, maximum=maximum, ref=ref )
saltstack/salt
salt/thorium/calc.py
mode
python
def mode(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mode of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mode: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mode', minimum=minimum, maximum=maximum, ref=ref )
Calculates the mode of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mode: - name: myregentry - num: 5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L273-L293
[ "def calc(name, num, oper, minimum=0, maximum=0, ref=None):\n '''\n Perform a calculation on the ``num`` most recent values. Requires a list.\n Valid values for ``oper`` are:\n\n - add: Add last ``num`` values together\n - mul: Multiple last ``num`` values together\n - mean: Calculate mean of last ``num`` values\n - median: Calculate median of last ``num`` values\n - median_low: Calculate low median of last ``num`` values\n - median_high: Calculate high median of last ``num`` values\n - median_grouped: Calculate grouped median of last ``num`` values\n - mode: Calculate mode of last ``num`` values\n\n USAGE:\n\n .. code-block:: yaml\n\n foo:\n calc.calc:\n - name: myregentry\n - num: 5\n - oper: mean\n '''\n ret = {'name': name,\n 'changes': {},\n 'comment': '',\n 'result': True}\n if name not in __reg__:\n ret['comment'] = '{0} not found in register'.format(name)\n ret['result'] = False\n\n def opadd(vals):\n sum = 0\n for val in vals:\n sum = sum + val\n return sum\n\n def opmul(vals):\n prod = 0\n for val in vals:\n prod = prod * val\n return prod\n\n ops = {\n 'add': opadd,\n 'mul': opmul,\n 'mean': statistics.mean,\n 'median': statistics.median,\n 'median_low': statistics.median_low,\n 'median_high': statistics.median_high,\n 'median_grouped': statistics.median_grouped,\n 'mode': statistics.mode,\n }\n\n count = 0\n vals = []\n __reg__[name]['val'].reverse()\n for regitem in __reg__[name]['val']:\n count += 1\n if count > num:\n break\n if ref is None:\n vals.append(regitem)\n else:\n vals.append(regitem[ref])\n\n answer = ops[oper](vals)\n\n if minimum > 0 and answer < minimum:\n ret['result'] = False\n\n if 0 < maximum < answer:\n ret['result'] = False\n\n ret['changes'] = {\n 'Number of values': len(vals),\n 'Operator': oper,\n 'Answer': answer,\n }\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. .. versionadded:: 2016.11.0 :depends: statistics PyPi module ''' # import python libs from __future__ import absolute_import, print_function, unicode_literals try: import statistics HAS_STATS = True except ImportError: HAS_STATS = False def __virtual__(): ''' The statistics module must be pip installed ''' return HAS_STATS def calc(name, num, oper, minimum=0, maximum=0, ref=None): ''' Perform a calculation on the ``num`` most recent values. Requires a list. Valid values for ``oper`` are: - add: Add last ``num`` values together - mul: Multiple last ``num`` values together - mean: Calculate mean of last ``num`` values - median: Calculate median of last ``num`` values - median_low: Calculate low median of last ``num`` values - median_high: Calculate high median of last ``num`` values - median_grouped: Calculate grouped median of last ``num`` values - mode: Calculate mode of last ``num`` values USAGE: .. code-block:: yaml foo: calc.calc: - name: myregentry - num: 5 - oper: mean ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: ret['comment'] = '{0} not found in register'.format(name) ret['result'] = False def opadd(vals): sum = 0 for val in vals: sum = sum + val return sum def opmul(vals): prod = 0 for val in vals: prod = prod * val return prod ops = { 'add': opadd, 'mul': opmul, 'mean': statistics.mean, 'median': statistics.median, 'median_low': statistics.median_low, 'median_high': statistics.median_high, 'median_grouped': statistics.median_grouped, 'mode': statistics.mode, } count = 0 vals = [] __reg__[name]['val'].reverse() for regitem in __reg__[name]['val']: count += 1 if count > num: break if ref is None: vals.append(regitem) else: vals.append(regitem[ref]) answer = ops[oper](vals) if minimum > 0 and answer < minimum: ret['result'] = False if 0 < maximum < answer: ret['result'] = False ret['changes'] = { 'Number of values': len(vals), 'Operator': oper, 'Answer': answer, } return ret def add(name, num, minimum=0, maximum=0, ref=None): ''' Adds together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.add: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='add', minimum=minimum, maximum=maximum, ref=ref ) def mul(name, num, minimum=0, maximum=0, ref=None): ''' Multiplies together the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mul: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mul', minimum=minimum, maximum=maximum, ref=ref ) def mean(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.mean: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='mean', minimum=minimum, maximum=maximum, ref=ref ) def median(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median', minimum=minimum, maximum=maximum, ref=ref ) def median_low(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_low', minimum=minimum, maximum=maximum, ref=ref ) def median_high(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the high mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_high: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_high', minimum=minimum, maximum=maximum, ref=ref ) def median_grouped(name, num, minimum=0, maximum=0, ref=None): ''' Calculates the grouped mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_grouped: - name: myregentry - num: 5 ''' return calc( name=name, num=num, oper='median_grouped', minimum=minimum, maximum=maximum, ref=ref )
saltstack/salt
salt/engines/libvirt_events.py
_get_libvirt_enum_string
python
def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown'
Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L156-L175
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_get_domain_event_detail
python
def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name
Convert event and detail numeric values into a tuple of human readable strings
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L178-L189
[ "def _get_libvirt_enum_string(prefix, value):\n '''\n Convert the libvirt enum integer value into a human readable string.\n\n :param prefix: start of the libvirt attribute to look for.\n :param value: integer to convert to string\n '''\n attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)]\n\n # Filter out the values starting with a common base as they match another enum\n prefixes = [_compute_subprefix(p) for p in attributes]\n counts = {p: prefixes.count(p) for p in prefixes}\n sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)]\n filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes]\n\n for candidate in filtered:\n if value == getattr(libvirt, ''.join((prefix, candidate))):\n name = candidate.lower().replace('_', ' ')\n return name\n return 'unknown'\n" ]
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_salt_send_event
python
def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data)
Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L192-L231
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_salt_send_domain_event
python
def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data)
Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L234-L254
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_lifecycle_cb
python
def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str })
Domain lifecycle events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L257-L266
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_rtc_change_cb
python
def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset })
Domain RTC change events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L276-L282
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_watchdog_cb
python
def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) })
Domain watchdog events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L285-L291
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_io_error_cb
python
def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason })
Domain I/O Error events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L294-L303
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_graphics_cb
python
def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] })
Domain graphics events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L306-L326
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_disk_change_cb
python
def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) })
Domain disk change events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L336-L345
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_tray_change_cb
python
def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) })
Domain tray change events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L348-L355
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_pmwakeup_cb
python
def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused })
Domain wakeup events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L358-L364
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_pmsuspend_cb
python
def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused })
Domain suspend events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L367-L373
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_balloon_change_cb
python
def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual })
Domain balloon change events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L376-L382
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_pmsuspend_disk_cb
python
def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused })
Domain disk suspend events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L385-L391
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_block_job_cb
python
def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) })
Domain block job events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L394-L402
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_device_removed_cb
python
def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev })
Domain device removal events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L405-L411
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_tunable_cb
python
def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params })
Domain tunable events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L414-L420
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_agent_lifecycle_cb
python
def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) })
Domain agent lifecycle events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L424-L431
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_device_added_cb
python
def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev })
Domain device addition events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L434-L440
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_migration_iteration_cb
python
def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration })
Domain migration iteration events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L444-L450
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_job_completed_cb
python
def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params })
Domain job completion events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L453-L459
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_device_removal_failed_cb
python
def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev })
Domain device removal failure events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L462-L468
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_metadata_change_cb
python
def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri })
Domain metadata change events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L471-L478
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_domain_event_block_threshold_cb
python
def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess })
Domain block threshold events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L481-L490
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_network_event_lifecycle_cb
python
def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused })
Network lifecycle events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L493-L505
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_pool_event_lifecycle_cb
python
def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused })
Storage pool lifecycle events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L508-L519
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_pool_event_refresh_cb
python
def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] })
Storage pool refresh events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L522-L532
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_nodedev_event_lifecycle_cb
python
def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused })
Node device lifecycle events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L535-L545
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_nodedev_event_update_cb
python
def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] })
Node device update events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L548-L557
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_secret_event_lifecycle_cb
python
def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused })
Secret lifecycle events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L560-L570
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_secret_event_value_changed_cb
python
def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] })
Secret value change events handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L573-L582
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_callbacks_cleanup
python
def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id)
Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L595-L608
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_register_callback
python
def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event})
Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L611-L643
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
_append_callback_id
python
def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id)
Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L646-L657
null
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
saltstack/salt
salt/engines/libvirt_events.py
start
python
def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all' ''' if filters is None: filters = ['all'] try: libvirt.virEventRegisterDefaultImpl() cnx = libvirt.openReadOnly(uri) log.debug('Opened libvirt uri: %s', cnx.getURI()) callback_ids = {} all_filters = "all" in filters for obj, event_defs in CALLBACK_DEFS.items(): for event, real_id in event_defs: event_filter = "/".join((obj, event)) if event_filter not in filters and obj not in filters and not all_filters: continue registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id) if registered_id: _append_callback_id(callback_ids, obj, registered_id) exit_loop = False while not exit_loop: exit_loop = libvirt.virEventRunDefaultImpl() < 0 log.debug('=== in the loop exit_loop %s ===', exit_loop) except Exception as err: # pylint: disable=broad-except log.exception(err) finally: _callbacks_cleanup(cnx, callback_ids) _cleanup(cnx)
Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of the salt event tag to use. Defaults to 'salt/engines/libvirt_events' :param filters: the list of event of listen on. Defaults to 'all'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L660-L702
[ "def _register_callback(cnx, tag_prefix, obj, event, real_id):\n '''\n Helper function registering a callback\n\n :param cnx: libvirt connection\n :param tag_prefix: salt event tag prefix to use\n :param obj: the libvirt object name for the event. Needs to\n be one of the REGISTER_FUNCTIONS keys.\n :param event: the event type name.\n :param real_id: the libvirt name of an alternative event id to use or None\n\n :rtype integer value needed to deregister the callback\n '''\n libvirt_name = real_id\n if real_id is None:\n libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper()\n\n if not hasattr(libvirt, libvirt_name):\n log.warning('Skipping \"%s/%s\" events: libvirt too old', obj, event)\n return None\n\n libvirt_id = getattr(libvirt, libvirt_name)\n callback_name = \"_{0}_event_{1}_cb\".format(obj, event)\n callback = globals().get(callback_name, None)\n if callback is None:\n log.error('Missing function %s in engine', callback_name)\n return None\n\n register = getattr(cnx, REGISTER_FUNCTIONS[obj])\n return register(None, libvirt_id, callback,\n {'prefix': tag_prefix,\n 'object': obj,\n 'event': event})\n", "def _cleanup(cnx):\n '''\n Close the libvirt connection\n\n :param cnx: libvirt connection\n '''\n log.debug('Closing libvirt connection: %s', cnx.getURI())\n cnx.close()\n", "def _callbacks_cleanup(cnx, callback_ids):\n '''\n Unregister all the registered callbacks\n\n :param cnx: libvirt connection\n :param callback_ids: dictionary mapping a libvirt object type to an ID list\n of callbacks to deregister\n '''\n for obj, ids in callback_ids.items():\n register_name = REGISTER_FUNCTIONS[obj]\n deregister_name = register_name.replace('Reg', 'Dereg')\n deregister = getattr(cnx, deregister_name)\n for callback_id in ids:\n deregister(callback_id)\n", "def _append_callback_id(ids, obj, callback_id):\n '''\n Helper function adding a callback ID to the IDs dict.\n The callback ids dict maps an object to event callback ids.\n\n :param ids: dict of callback IDs to update\n :param obj: one of the keys of REGISTER_FUNCTIONS\n :param callback_id: the result of _register_callback\n '''\n if obj not in ids:\n ids[obj] = []\n ids[obj].append(callback_id)\n" ]
# -*- coding: utf-8 -*- ''' An engine that listens for libvirt events and resends them to the salt event bus. The minimal configuration is the following and will listen to all events on the local hypervisor and send them with a tag starting with ``salt/engines/libvirt_events``: .. code-block:: yaml engines: - libvirt_events Note that the automatically-picked libvirt connection will depend on the value of ``uri_default`` in ``/etc/libvirt/libvirt.conf``. To force using another connection like the local LXC libvirt driver, set the ``uri`` property as in the following example configuration. .. code-block:: yaml engines: - libvirt_events: uri: lxc:/// tag_prefix: libvirt filters: - domain/lifecycle - domain/reboot - pool Filters is a list of event types to relay to the event bus. Items in this list can be either one of the main types (``domain``, ``network``, ``pool``, ``nodedev``, ``secret``), ``all`` or a more precise filter. These can be done with values like <main_type>/<subtype>. The possible values are in the CALLBACK_DEFS constant. If the filters list contains ``all``, all events will be relayed. Be aware that the list of events increases with libvirt versions, for example network events have been added in libvirt 1.2.1. Running the engine on non-root ------------------------------ Running this engine as non-root requires a special attention, which is surely the case for the master running as user `salt`. The engine is likely to fail to connect to libvirt with an error like this one: [ERROR ] authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.monitor' To fix this, the user running the engine, for example the salt-master, needs to have the rights to connect to libvirt in the machine polkit config. A polkit rule like the following one will allow `salt` user to connect to libvirt: .. code-block:: javascript polkit.addRule(function(action, subject) { if (action.id.indexOf("org.libvirt") == 0 && subject.user == "salt") { return polkit.Result.YES; } }); :depends: libvirt 1.0.0+ python binding .. versionadded:: 2019.2.0 ''' from __future__ import absolute_import, unicode_literals, print_function import logging # Import salt libs import salt.utils.event # pylint: disable=no-name-in-module,import-error from salt.ext.six.moves.urllib.parse import urlparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) try: import libvirt except ImportError: libvirt = None # pylint: disable=invalid-name def __virtual__(): ''' Only load if libvirt python binding is present ''' if libvirt is None: msg = 'libvirt module not found' elif libvirt.getVersion() < 1000000: msg = 'libvirt >= 1.0.0 required' else: msg = '' return not bool(msg), msg REGISTER_FUNCTIONS = { 'domain': 'domainEventRegisterAny', 'network': 'networkEventRegisterAny', 'pool': 'storagePoolEventRegisterAny', 'nodedev': 'nodeDeviceEventRegisterAny', 'secret': 'secretEventRegisterAny' } # Handle either BLOCK_JOB or BLOCK_JOB_2, but prefer the latter if hasattr(libvirt, 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2'): BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2' else: BLOCK_JOB_ID = 'VIR_DOMAIN_EVENT_ID_BLOCK_JOB' CALLBACK_DEFS = { 'domain': (('lifecycle', None), ('reboot', None), ('rtc_change', None), ('watchdog', None), ('graphics', None), ('io_error', 'VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON'), ('control_error', None), ('disk_change', None), ('tray_change', None), ('pmwakeup', None), ('pmsuspend', None), ('balloon_change', None), ('pmsuspend_disk', None), ('device_removed', None), ('block_job', BLOCK_JOB_ID), ('tunable', None), ('agent_lifecycle', None), ('device_added', None), ('migration_iteration', None), ('job_completed', None), ('device_removal_failed', None), ('metadata_change', None), ('block_threshold', None)), 'network': (('lifecycle', None),), 'pool': (('lifecycle', None), ('refresh', None)), 'nodedev': (('lifecycle', None), ('update', None)), 'secret': (('lifecycle', None), ('value_changed', None)) } def _compute_subprefix(attr): ''' Get the part before the first '_' or the end of attr including the potential '_' ''' return ''.join((attr.split('_')[0], '_' if len(attr.split('_')) > 1 else '')) def _get_libvirt_enum_string(prefix, value): ''' Convert the libvirt enum integer value into a human readable string. :param prefix: start of the libvirt attribute to look for. :param value: integer to convert to string ''' attributes = [attr[len(prefix):] for attr in libvirt.__dict__ if attr.startswith(prefix)] # Filter out the values starting with a common base as they match another enum prefixes = [_compute_subprefix(p) for p in attributes] counts = {p: prefixes.count(p) for p in prefixes} sub_prefixes = [p for p, count in counts.items() if count > 1 or (p.endswith('_') and p[:-1] in prefixes)] filtered = [attr for attr in attributes if _compute_subprefix(attr) not in sub_prefixes] for candidate in filtered: if value == getattr(libvirt, ''.join((prefix, candidate))): name = candidate.lower().replace('_', ' ') return name return 'unknown' def _get_domain_event_detail(event, detail): ''' Convert event and detail numeric values into a tuple of human readable strings ''' event_name = _get_libvirt_enum_string('VIR_DOMAIN_EVENT_', event) if event_name == 'unknown': return event_name, 'unknown' prefix = 'VIR_DOMAIN_EVENT_{0}_'.format(event_name.upper()) detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name def _salt_send_event(opaque, conn, data): ''' Convenience function adding common data to the event and sending it on the salt event bus. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param data: additional event data dict to send ''' tag_prefix = opaque['prefix'] object_type = opaque['object'] event_type = opaque['event'] # Prepare the connection URI to fit in the tag # qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system uri = urlparse(conn.getURI()) uri_tag = [uri.scheme] if uri.netloc: uri_tag.append(uri.netloc) path = uri.path.strip('/') if path: uri_tag.append(path) uri_str = "/".join(uri_tag) # Append some common data all_data = { 'uri': conn.getURI() } all_data.update(data) tag = '/'.join((tag_prefix, uri_str, object_type, event_type)) # Actually send the event in salt if __opts__.get('__role') == 'master': salt.utils.event.get_master_event( __opts__, __opts__['sock_dir']).fire_event(all_data, tag) else: __salt__['event.send'](tag, all_data) def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of the event :param event_data: additional event data dict to send ''' data = { 'domain': { 'name': domain.name(), 'id': domain.ID(), 'uuid': domain.UUIDString() }, 'event': event } data.update(event_data) _salt_send_event(opaque, conn, data) def _domain_event_lifecycle_cb(conn, domain, event, detail, opaque): ''' Domain lifecycle events handler ''' event_str, detail_str = _get_domain_event_detail(event, detail) _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'event': event_str, 'detail': detail_str }) def _domain_event_reboot_cb(conn, domain, opaque): ''' Domain reboot events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_rtc_change_cb(conn, domain, utcoffset, opaque): ''' Domain RTC change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'utcoffset': utcoffset }) def _domain_event_watchdog_cb(conn, domain, action, opaque): ''' Domain watchdog events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action) }) def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_IO_ERROR_', action), 'reason': reason }) def _domain_event_graphics_cb(conn, domain, phase, local, remote, auth, subject, opaque): ''' Domain graphics events handler ''' prefix = 'VIR_DOMAIN_EVENT_GRAPHICS_' def get_address(addr): ''' transform address structure into event data piece ''' return {'family': _get_libvirt_enum_string('{0}_ADDRESS_'.format(prefix), addr['family']), 'node': addr['node'], 'service': addr['service']} _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'phase': _get_libvirt_enum_string(prefix, phase), 'local': get_address(local), 'remote': get_address(remote), 'authScheme': auth, 'subject': [{'type': item[0], 'name': item[1]} for item in subject] }) def _domain_event_control_error_cb(conn, domain, opaque): ''' Domain control error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], {}) def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) }) def _domain_event_tray_change_cb(conn, domain, dev, reason, opaque): ''' Domain tray change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_TRAY_CHANGE_', reason) }) def _domain_event_pmwakeup_cb(conn, domain, reason, opaque): ''' Domain wakeup events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): ''' Domain suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_balloon_change_cb(conn, domain, actual, opaque): ''' Domain balloon change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual }) def _domain_event_pmsuspend_disk_cb(conn, domain, reason, opaque): ''' Domain disk suspend events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'reason': 'unknown' # currently unused }) def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque): ''' Domain block job events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'disk': disk, 'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type), 'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status) }) def _domain_event_device_removed_cb(conn, domain, dev, opaque): ''' Domain device removal events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_tunable_cb(conn, domain, params, opaque): ''' Domain tunable events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) # pylint: disable=invalid-name def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque): ''' Domain agent lifecycle events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state), 'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason) }) def _domain_event_device_added_cb(conn, domain, dev, opaque): ''' Domain device addition events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) # pylint: disable=invalid-name def _domain_event_migration_iteration_cb(conn, domain, iteration, opaque): ''' Domain migration iteration events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'iteration': iteration }) def _domain_event_job_completed_cb(conn, domain, params, opaque): ''' Domain job completion events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'params': params }) def _domain_event_device_removal_failed_cb(conn, domain, dev, opaque): ''' Domain device removal failure events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev }) def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque): ''' Domain metadata change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype), 'nsuri': nsuri }) def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): ''' Domain block threshold events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess }) def _network_event_lifecycle_cb(conn, net, event, detail, opaque): ''' Network lifecycle events handler ''' _salt_send_event(opaque, conn, { 'network': { 'name': net.name(), 'uuid': net.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_NETWORK_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_lifecycle_cb(conn, pool, event, detail, opaque): ''' Storage pool lifecycle events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_STORAGE_POOL_EVENT_', event), 'detail': 'unknown' # currently unused }) def _pool_event_refresh_cb(conn, pool, opaque): ''' Storage pool refresh events handler ''' _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] }) def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque): ''' Node device lifecycle events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event), 'detail': 'unknown' # currently unused }) def _nodedev_event_update_cb(conn, dev, opaque): ''' Node device update events handler ''' _salt_send_event(opaque, conn, { 'nodedev': { 'name': dev.name() }, 'event': opaque['event'] }) def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque): ''' Secret lifecycle events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event), 'detail': 'unknown' # currently unused }) def _secret_event_value_changed_cb(conn, secret, opaque): ''' Secret value change events handler ''' _salt_send_event(opaque, conn, { 'secret': { 'uuid': secret.UUIDString() }, 'event': opaque['event'] }) def _cleanup(cnx): ''' Close the libvirt connection :param cnx: libvirt connection ''' log.debug('Closing libvirt connection: %s', cnx.getURI()) cnx.close() def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): register_name = REGISTER_FUNCTIONS[obj] deregister_name = register_name.replace('Reg', 'Dereg') deregister = getattr(cnx, deregister_name) for callback_id in ids: deregister(callback_id) def _register_callback(cnx, tag_prefix, obj, event, real_id): ''' Helper function registering a callback :param cnx: libvirt connection :param tag_prefix: salt event tag prefix to use :param obj: the libvirt object name for the event. Needs to be one of the REGISTER_FUNCTIONS keys. :param event: the event type name. :param real_id: the libvirt name of an alternative event id to use or None :rtype integer value needed to deregister the callback ''' libvirt_name = real_id if real_id is None: libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) callback_name = "_{0}_event_{1}_cb".format(obj, event) callback = globals().get(callback_name, None) if callback is None: log.error('Missing function %s in engine', callback_name) return None register = getattr(cnx, REGISTER_FUNCTIONS[obj]) return register(None, libvirt_id, callback, {'prefix': tag_prefix, 'object': obj, 'event': event}) def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback ''' if obj not in ids: ids[obj] = [] ids[obj].append(callback_id)
saltstack/salt
salt/modules/status.py
_number
python
def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text
Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L59-L71
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
_get_boot_time_aix
python
def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs
Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L74-L94
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
_aix_loadavg
python
def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]}
Return the load average on AIX
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L97-L107
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
procs
python
def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret
Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L118-L154
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
custom
python
def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret
Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L157-L189
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
uptime
python
def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret
Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L192-L265
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
loadavg
python
def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]}
Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L268-L293
[ "def _aix_loadavg():\n '''\n Return the load average on AIX\n '''\n # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69\n uptime = __salt__['cmd.run']('uptime')\n ldavg = uptime.split('load average')\n load_avg = ldavg[1].split()\n return {'1-min': load_avg[1].strip(','),\n '5-min': load_avg[2].strip(','),\n '15-min': load_avg[3]}\n" ]
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
cpustats
python
def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)()
Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L296-L441
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
meminfo
python
def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)()
Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L444-L604
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
cpuinfo
python
def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)()
.. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L607-L812
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
diskstats
python
def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)()
.. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L815-L941
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
diskusage
python
def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret
Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L944-L1017
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
vmstats
python
def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)()
.. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1020-L1074
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
nproc
python
def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)()
Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1077-L1123
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)
saltstack/salt
salt/modules/status.py
netstats
python
def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ''' linux specific netstats implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: headers = [''] for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == headers[0]: index = len(headers) - 1 row = {} for field in range(index): if field < 1: continue else: row[headers[field]] = _number(comps[field]) rowname = headers[0].replace(':', '') ret[rowname] = row else: headers = comps return ret def freebsd_netstats(): return bsd_netstats() def bsd_netstats(): ''' bsd specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): if line.startswith('\t\t'): continue # Skip, too detailed if not line.startswith('\t'): key = line.split()[0].replace(':', '') ret[key] = {} else: comps = line.split() if comps[0].isdigit(): ret[key][' '.join(comps[1:])] = comps[0] return ret def sunos_netstats(): ''' sunos specific netstats implementation ''' ret = {} for line in __salt__['cmd.run']('netstat -s').splitlines(): line = line.replace('=', ' = ').split() if len(line) > 6: line.pop(0) if '=' in line: if len(line) >= 3: if line[2].isdigit() or line[2][0] == '-': line[2] = _number(line[2]) ret[line[0]] = line[2] if len(line) >= 6: if line[5].isdigit() or line[5][0] == '-': line[5] = _number(line[5]) ret[line[3]] = line[5] return ret def aix_netstats(): ''' AIX specific netstats implementation ''' ret = {} fields = [] procn = None proto_name = None for line in __salt__['cmd.run']('netstat -s').splitlines(): if not line: continue if not re.match(r'\s', line) and ':' in line: comps = line.split(':') proto_name = comps[0] ret[proto_name] = [] procn = len(ret[proto_name]) ret[proto_name].append({}) continue else: comps = line.split() comps[0] = comps[0].strip() if comps[0].isdigit(): ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0]) else: continue return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netstats, 'FreeBSD': bsd_netstats, 'OpenBSD': bsd_netstats, 'SunOS': sunos_netstats, 'AIX': aix_netstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)()
Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1126-L1251
null
# -*- coding: utf-8 -*- ''' Module for returning various status data about a minion. These data can be useful for compiling into stats later. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import datetime import os import re import logging import fnmatch import collections import copy import time import logging # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin # Import salt libs import salt.config import salt.minion import salt.utils.event import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.ext.six.moves import zip from salt.exceptions import CommandExecutionError log = logging.getLogger(__file__) __virtualname__ = 'status' __opts__ = {} # Don't shadow built-in's. __func_alias__ = { 'time_': 'time' } log = logging.getLogger(__name__) def __virtual__(): ''' Not all functions supported by Windows ''' if salt.utils.platform.is_windows(): return False, 'Windows platform is not supported by this module' return __virtualname__ def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text def _get_boot_time_aix(): ''' Return the number of seconds since boot time on AIX t=$(LC_ALL=POSIX ps -o etime= -p 1) d=0 h=0 case $t in *-*) d=${t%%-*}; t=${t#*-};; esac case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:})) t is 7-20:46:46 ''' boot_secs = 0 res = __salt__['cmd.run_all']('ps -o etime= -p 1') if res['retcode'] > 0: raise CommandExecutionError('Unable to find boot_time for pid 1.') bt_time = res['stdout'] days = bt_time.split('-') hms = days[1].split(':') boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2]) return boot_secs def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), '5-min': load_avg[2].strip(','), '15-min': load_avg[3]} def _aix_nproc(): ''' Return the maximun number of PROCESSES allowed per user on AIX ''' nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split() return _number(nprocs[1]) def procs(): ''' Return the process data .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.procs ''' # Get the user, pid and cmd ret = {} uind = 0 pind = 0 cind = 0 plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines() guide = plines.pop(0).split() if 'USER' in guide: uind = guide.index('USER') elif 'UID' in guide: uind = guide.index('UID') if 'PID' in guide: pind = guide.index('PID') if 'COMMAND' in guide: cind = guide.index('COMMAND') elif 'CMD' in guide: cind = guide.index('CMD') for line in plines: if not line: continue comps = line.split() ret[comps[pind]] = {'user': comps[uind], 'cmd': ' '.join(comps[cind:])} return ret def custom(): ''' Return a custom composite of status data and info for this minion, based on the minion config file. An example config like might be:: status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ] Where status refers to status.py, cpustats is the function where we get our data, and custom is this function It is followed by a list of keys that we want returned. This function is meant to replace all_status(), which returns anything and everything, which we probably don't want. By default, nothing is returned. Warning: Depending on what you include, there can be a LOT here! CLI Example: .. code-block:: bash salt '*' status.custom ''' ret = {} conf = __salt__['config.dot_vals']('status') for key, val in six.iteritems(conf): func = '{0}()'.format(key.split('.')[1]) vals = eval(func) # pylint: disable=W0123 for item in val: ret[item] = vals[item] return ret def uptime(): ''' Return the uptime for this system. .. versionchanged:: 2015.8.9 The uptime function was changed to return a dictionary of easy-to-read key/value pairs containing uptime information, instead of the output from a ``cmd.run`` call. .. versionchanged:: 2016.11.0 Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.uptime ''' curr_seconds = time.time() # Get uptime in seconds if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path)) with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): # note: some flavors/versions report the host uptime inside a zone # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584 res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time') if res['retcode'] > 0: raise CommandExecutionError('The boot_time kstat was not found.') seconds = int(curr_seconds - int(res['stdout'].split()[-1])) elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd(): bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') seconds = int(curr_seconds - int(bt_data)) elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin(): # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016 bt_data = __salt__['sysctl.get']('kern.boottime') if not bt_data: raise CommandExecutionError('Cannot find kern.boottime system parameter') data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '') uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]]) seconds = int(curr_seconds - uptime['sec']) elif salt.utils.platform.is_aix(): seconds = _get_boot_time_aix() else: return __salt__['cmd.run']('uptime') # Setup datetime and timedelta objects boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds) curr_time = datetime.datetime.utcfromtimestamp(curr_seconds) up_time = curr_time - boot_time # Construct return information ut_ret = { 'seconds': seconds, 'since_iso': boot_time.isoformat(), 'since_t': int(curr_seconds - seconds), 'days': up_time.days, 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), } if salt.utils.path.which('who'): who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep)) return ut_ret def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __grains__['kernel'] == 'AIX': return _aix_loadavg() try: load_avg = os.getloadavg() except AttributeError: # Some UNIX-based operating systems do not have os.getloadavg() raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform') return {'1-min': load_avg[0], '5-min': load_avg[1], '15-min': load_avg[2]} def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''' linux specific implementation of cpustats ''' ret = {} try: with salt.utils.files.fopen('/proc/stat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() if comps[0] == 'cpu': ret[comps[0]] = {'idle': _number(comps[4]), 'iowait': _number(comps[5]), 'irq': _number(comps[6]), 'nice': _number(comps[2]), 'softirq': _number(comps[7]), 'steal': _number(comps[8]), 'system': _number(comps[3]), 'user': _number(comps[1])} elif comps[0] == 'intr': ret[comps[0]] = {'total': _number(comps[1]), 'irqs': [_number(x) for x in comps[2:]]} elif comps[0] == 'softirq': ret[comps[0]] = {'total': _number(comps[1]), 'softirqs': [_number(x) for x in comps[2:]]} else: ret[comps[0]] = _number(comps[1]) return ret def freebsd_cpustats(): ''' freebsd specific implementation of cpustats ''' vmstat = __salt__['cmd.run']('vmstat -P').splitlines() vm0 = vmstat[0].split() cpu0loc = vm0.index('cpu0') vm1 = vmstat[1].split() usloc = vm1.index('us') vm2 = vmstat[2].split() cpuctr = 0 ret = {} for cpu in vm0[cpu0loc:]: ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]), 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]), 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), } cpuctr += 1 return ret def sunos_cpustats(): ''' sunos specific implementation of cpustats ''' mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines() fields = mpstat[0].split() ret = {} for cpu in mpstat: if cpu.startswith('CPU'): continue cpu = cpu.split() ret[_number(cpu[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpu[0])][fields[i]] = _number(cpu[i]) return ret def aix_cpustats(): ''' AIX specific implementation of cpustats ''' ret = {} ret['mpstat'] = [] procn = None fields = [] for line in __salt__['cmd.run']('mpstat -a').splitlines(): if not line: continue procn = len(ret['mpstat']) if line.startswith('System'): comps = line.split(':') ret['mpstat'].append({}) ret['mpstat'][procn]['system'] = {} cpu_comps = comps[1].split() for i in range(0, len(cpu_comps)): cpu_vals = cpu_comps[i].split('=') ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1] if line.startswith('cpu'): fields = line.split() continue if fields: cpustat = line.split() ret[_number(cpustat[0])] = {} for i in range(1, len(fields)-1): ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i]) return ret def openbsd_cpustats(): ''' openbsd specific implementation of cpustats ''' systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines() fields = systat[3].split() ret = {} for cpu in systat[4:]: cpu_line = cpu.split() cpu_idx = cpu_line[0] ret[cpu_idx] = {} for idx, field in enumerate(fields[1:]): ret[cpu_idx][field] = cpu_line[idx+1] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_cpustats, 'FreeBSD': freebsd_cpustats, 'OpenBSD': openbsd_cpustats, 'SunOS': sunos_cpustats, 'AIX': aix_cpustats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): ''' linux specific implementation of meminfo ''' ret = {} try: with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() comps[0] = comps[0].replace(':', '') ret[comps[0]] = { 'value': comps[1], } if len(comps) > 2: ret[comps[0]]['unit'] = comps[2] return ret def freebsd_meminfo(): ''' freebsd specific implementation of meminfo ''' sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines() sysctlvm = [x for x in sysctlvm if x.startswith('vm')] sysctlvm = [x.split(':') for x in sysctlvm] sysctlvm = [[y.strip() for y in x] for x in sysctlvm] sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty ret = {} for line in sysctlvm: ret[line[0]] = line[1] # Special handling for vm.total as it's especially important sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines() sysctlvmtot = [x for x in sysctlvmtot if x] ret['vm.vmtotal'] = sysctlvmtot return ret def aix_meminfo(): ''' AIX specific implementation of meminfo ''' ret = {} ret['svmon'] = [] ret['vmstat'] = [] procn = None fields = [] pagesize_flag = False for line in __salt__['cmd.run']('svmon -G').splitlines(): # Note: svmon is per-system # size inuse free pin virtual mmode #memory 1048576 1039740 8836 285078 474993 Ded #pg space 917504 2574 # # work pers clnt other #pin 248379 0 2107 34592 #in use 474993 0 564747 # #PageSize PoolSize inuse pgsp pin virtual #s 4 KB - 666956 2574 60726 102209 #m 64 KB - 23299 0 14022 23299 if not line: continue if re.match(r'\s', line): # assume fields line fields = line.split() continue if line.startswith('memory') or line.startswith('pin'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i + 1: ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1] continue if line.startswith('pg space') or line.startswith('in use'): procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() pg_space = '{0} {1}'.format(comps[0], comps[1]) ret['svmon'][procn][pg_space] = {} for i in range(0, len(fields)): if len(comps) > i + 2: ret['svmon'][procn][pg_space][fields[i]] = comps[i+2] continue if line.startswith('PageSize'): fields = line.split() pagesize_flag = False continue if pagesize_flag: procn = len(ret['svmon']) ret['svmon'].append({}) comps = line.split() ret['svmon'][procn][comps[0]] = {} for i in range(0, len(fields)): if len(comps) > i: ret['svmon'][procn][comps[0]][fields[i]] = comps[i] continue for line in __salt__['cmd.run']('vmstat -v').splitlines(): # Note: vmstat is per-system if not line: continue procn = len(ret['vmstat']) ret['vmstat'].append({}) comps = line.lstrip().split(' ', 1) ret['vmstat'][procn][comps[1]] = comps[0] return ret def openbsd_meminfo(): ''' openbsd specific implementation of meminfo ''' vmstat = __salt__['cmd.run']('vmstat').splitlines() # We're only interested in memory and page values which are printed # as subsequent fields. fields = ['active virtual pages', 'free list size', 'page faults', 'pages reclaimed', 'pages paged in', 'pages paged out', 'pages freed', 'pages scanned'] data = vmstat[2].split()[2:10] ret = dict(zip(fields, data)) return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo, 'OpenBSD': openbsd_meminfo, 'AIX': aix_meminfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo ''' def linux_cpuinfo(): ''' linux specific cpuinfo implementation ''' ret = {} try: with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split(':') comps[0] = comps[0].strip() if comps[0] == 'flags': ret[comps[0]] = comps[1].split() else: ret[comps[0]] = comps[1].strip() return ret def bsd_cpuinfo(): ''' bsd specific cpuinfo implementation ''' bsd_cmd = 'sysctl hw.model hw.ncpu' ret = {} if __grains__['kernel'].lower() in ['netbsd', 'openbsd']: sep = '=' else: sep = ':' for line in __salt__['cmd.run'](bsd_cmd).splitlines(): if not line: continue comps = line.split(sep) comps[0] = comps[0].strip() ret[comps[0]] = comps[1].strip() return ret def sunos_cpuinfo(): ''' sunos specific cpuinfo implementation ''' ret = {} ret['isainfo'] = {} for line in __salt__['cmd.run']('isainfo -x').splitlines(): # Note: isainfo is per-system and not per-cpu # Output Example: #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu if not line: continue comps = line.split(':') comps[0] = comps[0].strip() ret['isainfo'][comps[0]] = sorted(comps[1].strip().split()) ret['psrinfo'] = [] procn = None for line in __salt__['cmd.run']('psrinfo -v -p').splitlines(): # Output Example: #The physical processor has 6 cores and 12 virtual processors (0-5 12-17) # The core has 2 virtual processors (0 12) # The core has 2 virtual processors (1 13) # The core has 2 virtual processors (2 14) # The core has 2 virtual processors (3 15) # The core has 2 virtual processors (4 16) # The core has 2 virtual processors (5 17) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz #The physical processor has 6 cores and 12 virtual processors (6-11 18-23) # The core has 2 virtual processors (6 18) # The core has 2 virtual processors (7 19) # The core has 2 virtual processors (8 20) # The core has 2 virtual processors (9 21) # The core has 2 virtual processors (10 22) # The core has 2 virtual processors (11 23) # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz) # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz # # Output Example 2: #The physical processor has 4 virtual processors (0-3) # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz) # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz if not line: continue if line.startswith('The physical processor'): procn = len(ret['psrinfo']) line = line.split() ret['psrinfo'].append({}) if 'cores' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['cores'] = _number(line[4]) ret['psrinfo'][procn]['topology']['threads'] = _number(line[7]) elif 'virtual' in line: ret['psrinfo'][procn]['topology'] = {} ret['psrinfo'][procn]['topology']['threads'] = _number(line[4]) elif line.startswith(' ' * 6): # 3x2 space indent ret['psrinfo'][procn]['name'] = line.strip() elif line.startswith(' ' * 4): # 2x2 space indent line = line.strip().split() ret['psrinfo'][procn]['vendor'] = line[1][1:] ret['psrinfo'][procn]['family'] = _number(line[4]) ret['psrinfo'][procn]['model'] = _number(line[6]) ret['psrinfo'][procn]['step'] = _number(line[8]) ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1]) return ret def aix_cpuinfo(): ''' AIX specific cpuinfo implementation ''' ret = {} ret['prtconf'] = [] ret['lparstat'] = [] procn = None for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #prtconf | grep -i "Processor" #Processor Type: PowerPC_POWER7 #Processor Implementation Mode: POWER 7 #Processor Version: PV_7_Compat #Number Of Processors: 2 #Processor Clock Speed: 3000 MHz # Model Implementation: Multiple Processor, PCI bus # + proc0 Processor # + proc4 Processor if not line: continue procn = len(ret['prtconf']) if line.startswith('Processor') or line.startswith('Number'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines(): # Note: prtconf is per-system and not per-cpu # Output Example: #CPU Type: 64-bit if not line: continue procn = len(ret['prtconf']) if line.startswith('CPU'): ret['prtconf'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['prtconf'][procn][comps[0]] = comps[1] else: continue for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines(): # Note: lparstat is per-system and not per-cpu # Output Example: #Online Virtual CPUs : 2 #Maximum Virtual CPUs : 2 #Minimum Virtual CPUs : 1 #Maximum Physical CPUs in system : 32 #Active Physical CPUs in system : 32 #Active CPUs in Pool : 32 #Shared Physical CPUs in system : 32 #Physical CPU Percentage : 25.00% #Desired Virtual CPUs : 2 if not line: continue procn = len(ret['lparstat']) ret['lparstat'].append({}) comps = line.split(':') comps[0] = comps[0].rstrip() ret['lparstat'][procn][comps[0]] = comps[1] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_cpuinfo, 'FreeBSD': bsd_cpuinfo, 'NetBSD': bsd_cpuinfo, 'OpenBSD': bsd_cpuinfo, 'SunOS': sunos_cpuinfo, 'AIX': aix_cpuinfo, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskstats(): ''' .. versionchanged:: 2016.3.2 Return the disk stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.diskstats ''' def linux_diskstats(): ''' linux specific implementation of diskstats ''' ret = {} try: with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[2]] = { 'major': _number(comps[0]), 'minor': _number(comps[1]), 'device': _number(comps[2]), 'reads_issued': _number(comps[3]), 'reads_merged': _number(comps[4]), 'sectors_read': _number(comps[5]), 'ms_spent_reading': _number(comps[6]), 'writes_completed': _number(comps[7]), 'writes_merged': _number(comps[8]), 'sectors_written': _number(comps[9]), 'ms_spent_writing': _number(comps[10]), 'io_in_progress': _number(comps[11]), 'ms_spent_in_io': _number(comps[12]), 'weighted_ms_spent_in_io': _number(comps[13]) } return ret def generic_diskstats(): ''' generic implementation of diskstats note: freebsd and sunos ''' ret = {} iostat = __salt__['cmd.run']('iostat -xzd').splitlines() header = iostat[1] for line in iostat[2:]: comps = line.split() ret[comps[0]] = {} for metric, value in zip(header.split()[1:], comps[1:]): ret[comps[0]][metric] = _number(value) return ret def aix_diskstats(): ''' AIX specific implementation of diskstats ''' ret = {} procn = None fields = [] disk_name = '' disk_mode = '' for line in __salt__['cmd.run']('iostat -dDV').splitlines(): # Note: iostat -dDV is per-system # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk0 xfer: %tm_act bps tps bread bwrtn # 0.0 0.8 0.0 0.0 0.8 # read: rps avgserv minserv maxserv timeouts fails # 0.0 2.5 0.3 12.4 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.3 0.2 0.7 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.3 0.0 5.3 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #have new disk dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() ret[disk_name] = [] procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() procn = len(ret[disk_name]) ret[disk_name].append({}) ret[disk_name][procn][disk_mode] = {} else: comps = line.split() for i in range(0, len(fields)): if len(comps) > i: ret[disk_name][procn][disk_mode][fields[i]] = comps[i] return ret # dict that return a function that does the right thing per platform get_version = { 'Linux': linux_diskstats, 'FreeBSD': generic_diskstats, 'SunOS': generic_diskstats, 'AIX': aix_diskstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def diskusage(*args): ''' Return the disk usage for this minion Usage:: salt '*' status.diskusage [paths and/or filesystem types] CLI Example: .. code-block:: bash salt '*' status.diskusage # usage for all filesystems salt '*' status.diskusage / /tmp # usage for / and /tmp salt '*' status.diskusage ext? # usage for ext[234] filesystems salt '*' status.diskusage / ext? # usage for / and all ext filesystems ''' selected = set() fstypes = set() if not args: # select all filesystems fstypes.add('*') else: for arg in args: if arg.startswith('/'): # select path selected.add(arg) else: # select fstype fstypes.add(arg) if fstypes: # determine which mount points host the specified fstypes regex = re.compile( '|'.join( fnmatch.translate(fstype).format('(%s)') for fstype in fstypes ) ) # ifile source of data varies with OS, otherwise all the same if __grains__['kernel'] == 'Linux': try: with salt.utils.files.fopen('/proc/mounts', 'r') as fp_: ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines() except OSError: return {} elif __grains__['kernel'] in ('FreeBSD', 'SunOS'): ifile = __salt__['cmd.run']('mount -p').splitlines() else: raise CommandExecutionError('status.diskusage not yet supported on this platform') for line in ifile: comps = line.split() if __grains__['kernel'] == 'SunOS': if len(comps) >= 4: mntpt = comps[2] fstype = comps[3] if regex.match(fstype): selected.add(mntpt) else: if len(comps) >= 3: mntpt = comps[1] fstype = comps[2] if regex.match(fstype): selected.add(mntpt) # query the filesystems disk usage ret = {} for path in selected: fsstats = os.statvfs(path) blksz = fsstats.f_bsize available = fsstats.f_bavail * blksz total = fsstats.f_blocks * blksz ret[path] = {"available": available, "total": total} return ret def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specific implementation of vmstats ''' ret = {} try: with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue comps = line.split() ret[comps[0]] = _number(comps[1]) return ret def generic_vmstats(): ''' generic implementation of vmstats note: works on FreeBSD, SunOS and OpenBSD (possibly others) ''' ret = {} for line in __salt__['cmd.run']('vmstat -s').splitlines(): comps = line.split() if comps[0].isdigit(): ret[' '.join(comps[1:])] = _number(comps[0].strip()) return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_vmstats, 'FreeBSD': generic_vmstats, 'OpenBSD': generic_vmstats, 'SunOS': generic_vmstats, 'AIX': generic_vmstats, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def nproc(): ''' Return the number of processing units available on this system .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for Darwin, FreeBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.nproc ''' def linux_nproc(): ''' linux specific implementation of nproc ''' try: return _number(__salt__['cmd.run']('nproc').strip()) except ValueError: return 0 def generic_nproc(): ''' generic implementation of nproc ''' ncpu_data = __salt__['sysctl.get']('hw.ncpu') if not ncpu_data: # We need at least one CPU to run return 1 else: return _number(ncpu_data) # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_nproc, 'Darwin': generic_nproc, 'FreeBSD': generic_nproc, 'OpenBSD': generic_nproc, 'AIX': _aix_nproc, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def netdev(): ''' .. versionchanged:: 2016.3.2 Return the network device stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.netdev ''' def linux_netdev(): ''' linux specific implementation of netdev ''' ret = {} try: with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): if not line: continue if line.find(':') < 0: continue comps = line.split() # Fix lines like eth0:9999..' comps[0] = line.split(':')[0].strip() # Support lines both like eth0:999 and eth0: 9999 comps.insert(1, line.split(':')[1].strip().split()[0]) ret[comps[0]] = {'iface': comps[0], 'rx_bytes': _number(comps[2]), 'rx_compressed': _number(comps[8]), 'rx_drop': _number(comps[5]), 'rx_errs': _number(comps[4]), 'rx_fifo': _number(comps[6]), 'rx_frame': _number(comps[7]), 'rx_multicast': _number(comps[9]), 'rx_packets': _number(comps[3]), 'tx_bytes': _number(comps[10]), 'tx_carrier': _number(comps[16]), 'tx_colls': _number(comps[15]), 'tx_compressed': _number(comps[17]), 'tx_drop': _number(comps[13]), 'tx_errs': _number(comps[12]), 'tx_fifo': _number(comps[14]), 'tx_packets': _number(comps[11])} return ret def freebsd_netdev(): ''' freebsd specific implementation of netdev ''' _dict_tree = lambda: collections.defaultdict(_dict_tree) ret = _dict_tree() netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines() netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:] header = netstat[0].split() for line in netstat[1:]: comps = line.split() for i in range(4, 13): # The columns we want ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i]) return ret def sunos_netdev(): ''' sunos specific implementation of netdev ''' ret = {} ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6 for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']: # fetch device info netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines() # prepare data netstat_ipv4[0] = netstat_ipv4[0].split() netstat_ipv4[1] = netstat_ipv4[1].split() netstat_ipv6[0] = netstat_ipv6[0].split() netstat_ipv6[1] = netstat_ipv6[1].split() # add data ret[dev] = {} for i in range(len(netstat_ipv4[0])-1): if netstat_ipv4[0][i] == 'Name': continue if netstat_ipv4[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i] else: ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i]) for i in range(len(netstat_ipv6[0])-1): if netstat_ipv6[0][i] == 'Name': continue if netstat_ipv6[0][i] in ['Address', 'Net/Dest']: ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i] else: ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i]) return ret def aix_netdev(): ''' AIX specific implementation of netdev ''' ret = {} fields = [] procn = None for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys(): # fetch device info #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0 #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0 #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6 #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines() netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines() # add data ret[dev] = [] for line in netstat_ipv4: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv4'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv4'][fields[i]] = comps[i] for line in netstat_ipv6: if line.startswith('Name'): fields = line.split() continue comps = line.split() if len(comps) < 3: raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line)) if comps[2].startswith('link'): continue procn = len(ret[dev]) ret[dev].append({}) ret[dev][procn]['ipv6'] = {} for i in range(1, len(fields)): if len(comps) > i: ret[dev][procn]['ipv6'][fields[i]] = comps[i] return ret # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_netdev, 'FreeBSD': freebsd_netdev, 'SunOS': sunos_netdev, 'AIX': aix_netdev, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def w(): # pylint: disable=C0103 ''' Return a list of logged in users for this minion, using the w command CLI Example: .. code-block:: bash salt '*' status.w ''' def linux_w(): ''' Linux specific implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -fh').splitlines() for row in users: if not row: continue comps = row.split() rec = {'idle': comps[3], 'jcpu': comps[4], 'login': comps[2], 'pcpu': comps[5], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[6:])} user_list.append(rec) return user_list def bsd_w(): ''' Generic BSD implementation for w ''' user_list = [] users = __salt__['cmd.run']('w -h').splitlines() for row in users: if not row: continue comps = row.split() rec = {'from': comps[2], 'idle': comps[4], 'login': comps[3], 'tty': comps[1], 'user': comps[0], 'what': ' '.join(comps[5:])} user_list.append(rec) return user_list # dict that returns a function that does the right thing per platform get_version = { 'Darwin': bsd_w, 'FreeBSD': bsd_w, 'Linux': linux_w, 'OpenBSD': bsd_w, } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def all_status(): ''' Return a composite of all status data and info for this minion. Warning: There is a LOT here! CLI Example: .. code-block:: bash salt '*' status.all_status ''' return {'cpuinfo': cpuinfo(), 'cpustats': cpustats(), 'diskstats': diskstats(), 'diskusage': diskusage(), 'loadavg': loadavg(), 'meminfo': meminfo(), 'netdev': netdev(), 'netstats': netstats(), 'uptime': uptime(), 'vmstats': vmstats(), 'w': w()} def pid(sig): ''' Return the PID or an empty string if the process is running or not. Pass a signature to use to find the process via ps. Note you can pass a Python-compatible regular expression to return all pids of processes matching the regexp. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.pid <sig> ''' cmd = __grains__['ps'] output = __salt__['cmd.run_stdout'](cmd, python_shell=True) pids = '' for line in output.splitlines(): if 'status.pid' in line: continue if re.search(sig, line): if pids: pids += '\n' pids += line.split()[1] return pids def version(): ''' Return the system version for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.version ''' def linux_version(): ''' linux specific implementation of version ''' try: with salt.utils.files.fopen('/proc/version', 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()).strip() except IOError: return {} def bsd_version(): ''' bsd specific implementation of version ''' return __salt__['cmd.run']('sysctl -n kern.version') # dict that returns a function that does the right thing per platform get_version = { 'Linux': linux_version, 'FreeBSD': bsd_version, 'OpenBSD': bsd_version, 'AIX': lambda: __salt__['cmd.run']('oslevel -s'), } errmsg = 'This method is unsupported on the current operating system!' return get_version.get(__grains__['kernel'], lambda: errmsg)() def master(master=None, connected=True): ''' .. versionadded:: 2014.7.0 Return the connection status with master. Fire an event if the connection to master is not as expected. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, it must be resolvable to a valid IPv4 address. .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.master ''' master_ips = None if master: master_ips = salt.utils.network.host_to_ips(master) if not master_ips: return master_connection_status = False port = __salt__['config.get']('publish_port', default=4505) connected_ips = salt.utils.network.remote_port_tcp(port) # Get connection status for master for master_ip in master_ips: if master_ip in connected_ips: master_connection_status = True break # Connection to master is not as expected if master_connection_status is not connected: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) if master_connection_status: event.fire_event({'master': master}, salt.minion.master_event(type='connected')) else: event.fire_event({'master': master}, salt.minion.master_event(type='disconnected')) return master_connection_status def ping_master(master): ''' .. versionadded:: 2016.3.0 Sends ping request to the given master. Fires '__master_failback' event on success. Returns bool result. CLI Example: .. code-block:: bash salt '*' status.ping_master localhost ''' if master is None or master == '': return False opts = copy.deepcopy(__opts__) opts['master'] = master if 'master_ip' in opts: # avoid 'master ip changed' warning del opts['master_ip'] opts.update(salt.minion.prep_ip_port(opts)) try: opts.update(salt.minion.resolve_dns(opts, fallback=False)) except Exception: return False timeout = opts.get('auth_timeout', 60) load = {'cmd': 'ping'} result = False channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear') try: payload = channel.send(load, tries=0, timeout=timeout) result = True except Exception as e: pass if result: event = salt.utils.event.get_event('minion', opts=__opts__, listen=False) event.fire_event({'master': master}, salt.minion.master_event(type='failback')) return result def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' if not opts: opts = __opts__ if 'proxy' not in opts: return False # fail proxy_keepalive_fn = proxy_name+'.alive' if proxy_keepalive_fn not in __proxy__: return False # fail is_alive = __proxy__[proxy_keepalive_fn](opts) if not is_alive: minion_id = opts.get('proxyid', '') or opts.get('id', '') log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name) __proxy__[proxy_name+'.shutdown'](opts) # safely close connection __proxy__[proxy_name+'.init'](opts) # reopen connection log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name) return True # success def time_(format='%A, %d. %B %Y %I:%M%p'): ''' .. versionadded:: 2016.3.0 Return the current time on the minion, formatted based on the format parameter. Default date format: Monday, 27. July 2015 07:55AM CLI Example: .. code-block:: bash salt '*' status.time salt '*' status.time '%s' ''' dt = datetime.datetime.today() return dt.strftime(format)