repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/postgres.py | is_installed_extension | 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) | 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) | [
"def",
"is_installed_extension",
"(",
"name",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"installed_ext",
"=",
"ge... | Test if a specific extension is installed
CLI Example:
.. code-block:: bash
salt '*' postgres.is_installed_extension | [
"Test",
"if",
"a",
"specific",
"extension",
"is",
"installed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1514-L1539 | train |
saltstack/salt | salt/modules/postgres.py | create_metadata | 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 | 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 | [
"def",
"create_metadata",
"(",
"name",
",",
"ext_version",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"... | Get lifecycle information about an extension
CLI Example:
.. code-block:: bash
salt '*' postgres.create_metadata adminpack | [
"Get",
"lifecycle",
"information",
"about",
"an",
"extension"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1542-L1586 | train |
saltstack/salt | salt/modules/postgres.py | drop_extension | 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 | 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 | [
"def",
"drop_extension",
"(",
"name",
",",
"if_exists",
"=",
"None",
",",
"restrict",
"=",
"None",
",",
"cascade",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"pa... | Drop an installed postgresql extension
CLI Example:
.. code-block:: bash
salt '*' postgres.drop_extension 'adminpack' | [
"Drop",
"an",
"installed",
"postgresql",
"extension"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1589-L1645 | train |
saltstack/salt | salt/modules/postgres.py | create_extension | 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 | 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 | [
"def",
"create_extension",
"(",
"name",
",",
"if_not_exists",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"ext_version",
"=",
"None",
",",
"from_version",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",... | Install a postgresql extension
CLI Example:
.. code-block:: bash
salt '*' postgres.create_extension 'adminpack' | [
"Install",
"a",
"postgresql",
"extension"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1648-L1735 | train |
saltstack/salt | salt/modules/postgres.py | user_remove | 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) | 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) | [
"def",
"user_remove",
"(",
"username",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"return",
"_role_remove",
"(",
... | Removes a user from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.user_remove 'username' | [
"Removes",
"a",
"user",
"from",
"the",
"Postgres",
"server",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1738-L1760 | train |
saltstack/salt | salt/modules/postgres.py | group_create | 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) | 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) | [
"def",
"group_create",
"(",
"groupname",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"createdb",
"=",
"None",
",",
"createroles",
"=",
"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' | [
"Creates",
"a",
"Postgres",
"group",
".",
"A",
"group",
"is",
"postgres",
"is",
"similar",
"to",
"a",
"user",
"but",
"cannot",
"login",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1765-L1809 | train |
saltstack/salt | salt/modules/postgres.py | group_remove | 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) | 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) | [
"def",
"group_remove",
"(",
"groupname",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"return",
"_role_remove",
"(",... | Removes a group from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.group_remove 'groupname' | [
"Removes",
"a",
"group",
"from",
"the",
"Postgres",
"server",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1858-L1880 | train |
saltstack/salt | salt/modules/postgres.py | owner_to | 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 | 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 | [
"def",
"owner_to",
"(",
"dbname",
",",
"ownername",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"sqlfile",
"=",
"tempfile",
".",
"NamedTemporaryFile",
... | 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' | [
"Set",
"the",
"owner",
"of",
"all",
"schemas",
"functions",
"tables",
"views",
"and",
"sequences",
"to",
"the",
"given",
"username",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1883-L1955 | train |
saltstack/salt | salt/modules/postgres.py | schema_create | 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 | 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 | [
"def",
"schema_create",
"(",
"dbname",
",",
"name",
",",
"owner",
"=",
"None",
",",
"user",
"=",
"None",
",",
"db_user",
"=",
"None",
",",
"db_password",
"=",
"None",
",",
"db_host",
"=",
"None",
",",
"db_port",
"=",
"None",
")",
":",
"# check if schem... | 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' | [
"Creates",
"a",
"Postgres",
"schema",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1960-L1993 | train |
saltstack/salt | salt/modules/postgres.py | schema_remove | 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 | 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 | [
"def",
"schema_remove",
"(",
"dbname",
",",
"name",
",",
"user",
"=",
"None",
",",
"db_user",
"=",
"None",
",",
"db_password",
"=",
"None",
",",
"db_host",
"=",
"None",
",",
"db_port",
"=",
"None",
")",
":",
"# check if schema exists",
"if",
"not",
"sche... | 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 | [
"Removes",
"a",
"schema",
"from",
"the",
"Postgres",
"server",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1996-L2053 | train |
saltstack/salt | salt/modules/postgres.py | schema_exists | 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)) | 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)) | [
"def",
"schema_exists",
"(",
"dbname",
",",
"name",
",",
"user",
"=",
"None",
",",
"db_user",
"=",
"None",
",",
"db_password",
"=",
"None",
",",
"db_host",
"=",
"None",
",",
"db_port",
"=",
"None",
")",
":",
"return",
"bool",
"(",
"schema_get",
"(",
... | 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 | [
"Checks",
"if",
"a",
"schema",
"exists",
"on",
"the",
"Postgres",
"server",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2056-L2095 | train |
saltstack/salt | salt/modules/postgres.py | schema_get | 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 | 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 | [
"def",
"schema_get",
"(",
"dbname",
",",
"name",
",",
"user",
"=",
"None",
",",
"db_user",
"=",
"None",
",",
"db_password",
"=",
"None",
",",
"db_host",
"=",
"None",
",",
"db_port",
"=",
"None",
")",
":",
"all_schemas",
"=",
"schema_list",
"(",
"dbname... | 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 | [
"Return",
"a",
"dict",
"with",
"information",
"about",
"schemas",
"in",
"a",
"database",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2098-L2140 | train |
saltstack/salt | salt/modules/postgres.py | schema_list | 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 | 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 | [
"def",
"schema_list",
"(",
"dbname",
",",
"user",
"=",
"None",
",",
"db_user",
"=",
"None",
",",
"db_password",
"=",
"None",
",",
"db_host",
"=",
"None",
",",
"db_port",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"query",
"=",
"(",
"''",
".",
"... | 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 | [
"Return",
"a",
"dict",
"with",
"information",
"about",
"schemas",
"in",
"a",
"Postgres",
"database",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2143-L2198 | train |
saltstack/salt | salt/modules/postgres.py | language_list | 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 | 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 | [
"def",
"language_list",
"(",
"maintenance_db",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"query",
"=",
"'SELECT lanname AS \"Na... | .. 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 | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2201-L2253 | train |
saltstack/salt | salt/modules/postgres.py | language_exists | 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 | 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 | [
"def",
"language_exists",
"(",
"name",
",",
"maintenance_db",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"languages",
"=",
"language_list",
"(",
"main... | .. 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 | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2256-L2303 | train |
saltstack/salt | salt/modules/postgres.py | language_create | 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 | 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 | [
"def",
"language_create",
"(",
"name",
",",
"maintenance_db",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"if",
"language_exists",
"(",
"name",
",",
... | .. 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 | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2306-L2360 | train |
saltstack/salt | salt/modules/postgres.py | _make_default_privileges_list_query | 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 | 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 | [
"def",
"_make_default_privileges_list_query",
"(",
"name",
",",
"object_type",
",",
"prepend",
")",
":",
"if",
"object_type",
"==",
"'table'",
":",
"query",
"=",
"(",
"' '",
".",
"join",
"(",
"[",
"'SELECT defacl.defaclacl AS name'",
",",
"'FROM pg_default_acl defac... | Generate the SQL required for specific object type | [
"Generate",
"the",
"SQL",
"required",
"for",
"specific",
"object",
"type"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2420-L2480 | train |
saltstack/salt | salt/modules/postgres.py | _make_privileges_list_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 | 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 | [
"def",
"_make_privileges_list_query",
"(",
"name",
",",
"object_type",
",",
"prepend",
")",
":",
"if",
"object_type",
"==",
"'table'",
":",
"query",
"=",
"(",
"' '",
".",
"join",
"(",
"[",
"'SELECT relacl AS name'",
",",
"'FROM pg_catalog.pg_class c'",
",",
"'JO... | Generate the SQL required for specific object type | [
"Generate",
"the",
"SQL",
"required",
"for",
"specific",
"object",
"type"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2483-L2560 | train |
saltstack/salt | salt/modules/postgres.py | _get_object_owner | 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 | 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 | [
"def",
"_get_object_owner",
"(",
"name",
",",
"object_type",
",",
"prepend",
"=",
"'public'",
",",
"maintenance_db",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
... | Return the owner of a postgres object | [
"Return",
"the",
"owner",
"of",
"a",
"postgres",
"object"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2563-L2650 | train |
saltstack/salt | salt/modules/postgres.py | _validate_default_privileges | 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') | 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') | [
"def",
"_validate_default_privileges",
"(",
"object_type",
",",
"defprivs",
",",
"defprivileges",
")",
":",
"if",
"object_type",
"!=",
"'group'",
":",
"_defperms",
"=",
"[",
"_DEFAULT_PRIVILEGES_MAP",
"[",
"defperm",
"]",
"for",
"defperm",
"in",
"_DEFAULT_PRIVILEGE_... | Validate the supplied privileges | [
"Validate",
"the",
"supplied",
"privileges"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2653-L2674 | train |
saltstack/salt | salt/modules/postgres.py | _mod_defpriv_opts | 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 | 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 | [
"def",
"_mod_defpriv_opts",
"(",
"object_type",
",",
"defprivileges",
")",
":",
"object_type",
"=",
"object_type",
".",
"lower",
"(",
")",
"defprivileges",
"=",
"''",
"if",
"defprivileges",
"is",
"None",
"else",
"defprivileges",
"_defprivs",
"=",
"re",
".",
"s... | Format options | [
"Format",
"options"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2677-L2685 | train |
saltstack/salt | salt/modules/postgres.py | _process_defpriv_part | 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 | 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 | [
"def",
"_process_defpriv_part",
"(",
"defperms",
")",
":",
"_tmp",
"=",
"{",
"}",
"previous",
"=",
"None",
"for",
"defperm",
"in",
"defperms",
":",
"if",
"previous",
"is",
"None",
":",
"_tmp",
"[",
"_DEFAULT_PRIVILEGES_MAP",
"[",
"defperm",
"]",
"]",
"=",
... | Process part | [
"Process",
"part"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2688-L2704 | train |
saltstack/salt | salt/modules/postgres.py | _validate_privileges | 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') | 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') | [
"def",
"_validate_privileges",
"(",
"object_type",
",",
"privs",
",",
"privileges",
")",
":",
"if",
"object_type",
"!=",
"'group'",
":",
"_perms",
"=",
"[",
"_PRIVILEGES_MAP",
"[",
"perm",
"]",
"for",
"perm",
"in",
"_PRIVILEGE_TYPE_MAP",
"[",
"object_type",
"]... | Validate the supplied privileges | [
"Validate",
"the",
"supplied",
"privileges"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2707-L2728 | train |
saltstack/salt | salt/modules/postgres.py | _mod_priv_opts | 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 | 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 | [
"def",
"_mod_priv_opts",
"(",
"object_type",
",",
"privileges",
")",
":",
"object_type",
"=",
"object_type",
".",
"lower",
"(",
")",
"privileges",
"=",
"''",
"if",
"privileges",
"is",
"None",
"else",
"privileges",
"_privs",
"=",
"re",
".",
"split",
"(",
"r... | Format options | [
"Format",
"options"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2731-L2739 | train |
saltstack/salt | salt/modules/postgres.py | _process_priv_part | 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 | 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 | [
"def",
"_process_priv_part",
"(",
"perms",
")",
":",
"_tmp",
"=",
"{",
"}",
"previous",
"=",
"None",
"for",
"perm",
"in",
"perms",
":",
"if",
"previous",
"is",
"None",
":",
"_tmp",
"[",
"_PRIVILEGES_MAP",
"[",
"perm",
"]",
"]",
"=",
"False",
"previous"... | Process part | [
"Process",
"part"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2742-L2758 | train |
saltstack/salt | salt/modules/postgres.py | default_privileges_list | 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 | 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 | [
"def",
"default_privileges_list",
"(",
"name",
",",
"object_type",
",",
"prepend",
"=",
"'public'",
",",
"maintenance_db",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runa... | .. 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 | [
"..",
"versionadded",
"::",
"2019",
".",
"0",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2761-L2854 | train |
saltstack/salt | salt/modules/postgres.py | privileges_list | 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 | 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 | [
"def",
"privileges_list",
"(",
"name",
",",
"object_type",
",",
"prepend",
"=",
"'public'",
",",
"maintenance_db",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=... | .. 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 | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2857-L2953 | train |
saltstack/salt | salt/modules/postgres.py | has_default_privileges | 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 | 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 | [
"def",
"has_default_privileges",
"(",
"name",
",",
"object_name",
",",
"object_type",
",",
"defprivileges",
"=",
"None",
",",
"grant_option",
"=",
"None",
",",
"prepend",
"=",
"'public'",
",",
"maintenance_db",
"=",
"None",
",",
"user",
"=",
"None",
",",
"ho... | .. 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 | [
"..",
"versionadded",
"::",
"2019",
".",
"0",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L2956-L3071 | train |
saltstack/salt | salt/modules/postgres.py | has_privileges | 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 | 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 | [
"def",
"has_privileges",
"(",
"name",
",",
"object_name",
",",
"object_type",
",",
"privileges",
"=",
"None",
",",
"grant_option",
"=",
"None",
",",
"prepend",
"=",
"'public'",
",",
"maintenance_db",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",... | .. 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 | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3074-L3194 | train |
saltstack/salt | salt/modules/postgres.py | default_privileges_grant | 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 | 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 | [
"def",
"default_privileges_grant",
"(",
"name",
",",
"object_name",
",",
"object_type",
",",
"defprivileges",
"=",
"None",
",",
"grant_option",
"=",
"None",
",",
"prepend",
"=",
"'public'",
",",
"maintenance_db",
"=",
"None",
",",
"user",
"=",
"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 | [
"..",
"versionadded",
"::",
"2019",
".",
"0",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3197-L3328 | train |
saltstack/salt | salt/modules/postgres.py | default_privileges_revoke | 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 | 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 | [
"def",
"default_privileges_revoke",
"(",
"name",
",",
"object_name",
",",
"object_type",
",",
"defprivileges",
"=",
"None",
",",
"prepend",
"=",
"'public'",
",",
"maintenance_db",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
... | .. 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 | [
"..",
"versionadded",
"::",
"2019",
".",
"0",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3331-L3434 | train |
saltstack/salt | salt/modules/postgres.py | privileges_grant | 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 | 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 | [
"def",
"privileges_grant",
"(",
"name",
",",
"object_name",
",",
"object_type",
",",
"privileges",
"=",
"None",
",",
"grant_option",
"=",
"None",
",",
"prepend",
"=",
"'public'",
",",
"maintenance_db",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=... | .. 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 | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3437-L3573 | train |
saltstack/salt | salt/modules/postgres.py | privileges_revoke | 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 | 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 | [
"def",
"privileges_revoke",
"(",
"name",
",",
"object_name",
",",
"object_type",
",",
"privileges",
"=",
"None",
",",
"prepend",
"=",
"'public'",
",",
"maintenance_db",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"N... | .. 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 | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3576-L3684 | train |
saltstack/salt | salt/modules/postgres.py | datadir_init | 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 | 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 | [
"def",
"datadir_init",
"(",
"name",
",",
"auth",
"=",
"'password'",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"encoding",
"=",
"'UTF8'",
",",
"locale",
"=",
"None",
",",
"waldir",
"=",
"None",
",",
"checksums",
"=",
"False",
",",
"... | .. 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 | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3687-L3754 | train |
saltstack/salt | salt/modules/postgres.py | datadir_exists | 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) | 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) | [
"def",
"datadir_exists",
"(",
"name",
")",
":",
"_version_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"name",
",",
"'PG_VERSION'",
")",
"_config_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"name",
",",
"'postgresql.conf'",
")",
"return",
"os",
... | .. 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 | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L3757-L3775 | train |
saltstack/salt | salt/modules/eselect.py | exec_action | 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 | 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 | [
"def",
"exec_action",
"(",
"module",
",",
"action",
",",
"module_parameter",
"=",
"None",
",",
"action_parameter",
"=",
"None",
",",
"state_only",
"=",
"False",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'eselect --brief --colour=no {0} {1} {... | 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' | [
"Execute",
"an",
"arbitrary",
"action",
"on",
"a",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/eselect.py#L25-L69 | train |
saltstack/salt | salt/modules/eselect.py | get_modules | 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 | 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 | [
"def",
"get_modules",
"(",
")",
":",
"modules",
"=",
"[",
"]",
"module_list",
"=",
"exec_action",
"(",
"'modules'",
",",
"'list'",
",",
"action_parameter",
"=",
"'--only-names'",
")",
"if",
"not",
"module_list",
":",
"return",
"None",
"for",
"module",
"in",
... | List available ``eselect`` modules.
CLI Example:
.. code-block:: bash
salt '*' eselect.get_modules | [
"List",
"available",
"eselect",
"modules",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/eselect.py#L72-L90 | train |
saltstack/salt | salt/modules/eselect.py | get_target_list | 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 | 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 | [
"def",
"get_target_list",
"(",
"module",
",",
"action_parameter",
"=",
"None",
")",
":",
"exec_output",
"=",
"exec_action",
"(",
"module",
",",
"'list'",
",",
"action_parameter",
"=",
"action_parameter",
")",
"if",
"not",
"exec_output",
":",
"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 | [
"List",
"available",
"targets",
"for",
"the",
"given",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/eselect.py#L93-L121 | train |
saltstack/salt | salt/modules/eselect.py | get_current_target | 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 | 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 | [
"def",
"get_current_target",
"(",
"module",
",",
"module_parameter",
"=",
"None",
",",
"action_parameter",
"=",
"None",
")",
":",
"result",
"=",
"exec_action",
"(",
"module",
",",
"'show'",
",",
"module_parameter",
"=",
"module_parameter",
",",
"action_parameter",... | 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 | [
"Get",
"the",
"currently",
"selected",
"target",
"for",
"the",
"given",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/eselect.py#L124-L156 | train |
saltstack/salt | salt/modules/eselect.py | set_target | 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 | 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 | [
"def",
"set_target",
"(",
"module",
",",
"target",
",",
"module_parameter",
"=",
"None",
",",
"action_parameter",
"=",
"None",
")",
":",
"if",
"action_parameter",
":",
"action_parameter",
"=",
"'{0} {1}'",
".",
"format",
"(",
"action_parameter",
",",
"target",
... | 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 | [
"Set",
"the",
"target",
"for",
"the",
"given",
"module",
".",
"Target",
"can",
"be",
"specified",
"by",
"index",
"or",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/eselect.py#L159-L201 | train |
saltstack/salt | salt/thorium/calc.py | calc | 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 | 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 | [
"def",
"calc",
"(",
"name",
",",
"num",
",",
"oper",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
... | 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 | [
"Perform",
"a",
"calculation",
"on",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
".",
"Valid",
"values",
"for",
"oper",
"are",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L28-L108 | train |
saltstack/salt | salt/thorium/calc.py | add | 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
) | 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
) | [
"def",
"add",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
"=",
"name",
",",
"num",
"=",
"num",
",",
"oper",
"=",
"'add'",
",",
"minimum",
"=",
... | Adds together the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.add:
- name: myregentry
- num: 5 | [
"Adds",
"together",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L111-L131 | train |
saltstack/salt | salt/thorium/calc.py | mul | 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
) | 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
) | [
"def",
"mul",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
"=",
"name",
",",
"num",
"=",
"num",
",",
"oper",
"=",
"'mul'",
",",
"minimum",
"=",
... | Multiplies together the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mul:
- name: myregentry
- num: 5 | [
"Multiplies",
"together",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L134-L154 | train |
saltstack/salt | salt/thorium/calc.py | mean | 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
) | 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
) | [
"def",
"mean",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
"=",
"name",
",",
"num",
"=",
"num",
",",
"oper",
"=",
"'mean'",
",",
"minimum",
"=",
... | Calculates the mean of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mean:
- name: myregentry
- num: 5 | [
"Calculates",
"the",
"mean",
"of",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L157-L177 | train |
saltstack/salt | salt/thorium/calc.py | median | 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
) | 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
) | [
"def",
"median",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
"=",
"name",
",",
"num",
"=",
"num",
",",
"oper",
"=",
"'median'",
",",
"minimum",
"... | Calculates the mean of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.median:
- name: myregentry
- num: 5 | [
"Calculates",
"the",
"mean",
"of",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L180-L200 | train |
saltstack/salt | salt/thorium/calc.py | median_low | 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
) | 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
) | [
"def",
"median_low",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
"=",
"name",
",",
"num",
"=",
"num",
",",
"oper",
"=",
"'median_low'",
",",
"minim... | 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 | [
"Calculates",
"the",
"low",
"mean",
"of",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L203-L223 | train |
saltstack/salt | salt/thorium/calc.py | median_high | 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
) | 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
) | [
"def",
"median_high",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
"=",
"name",
",",
"num",
"=",
"num",
",",
"oper",
"=",
"'median_high'",
",",
"min... | 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 | [
"Calculates",
"the",
"high",
"mean",
"of",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L226-L246 | train |
saltstack/salt | salt/thorium/calc.py | median_grouped | 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
) | 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
) | [
"def",
"median_grouped",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
"=",
"name",
",",
"num",
"=",
"num",
",",
"oper",
"=",
"'median_grouped'",
",",
... | 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 | [
"Calculates",
"the",
"grouped",
"mean",
"of",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L249-L270 | train |
saltstack/salt | salt/thorium/calc.py | mode | 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
) | 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
) | [
"def",
"mode",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
"=",
"name",
",",
"num",
"=",
"num",
",",
"oper",
"=",
"'mode'",
",",
"minimum",
"=",
... | Calculates the mode of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mode:
- name: myregentry
- num: 5 | [
"Calculates",
"the",
"mode",
"of",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L273-L293 | train |
saltstack/salt | salt/engines/libvirt_events.py | _get_libvirt_enum_string | 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' | 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' | [
"def",
"_get_libvirt_enum_string",
"(",
"prefix",
",",
"value",
")",
":",
"attributes",
"=",
"[",
"attr",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"for",
"attr",
"in",
"libvirt",
".",
"__dict__",
"if",
"attr",
".",
"startswith",
"(",
"prefix",
")",
"]... | 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 | [
"Convert",
"the",
"libvirt",
"enum",
"integer",
"value",
"into",
"a",
"human",
"readable",
"string",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L156-L175 | train |
saltstack/salt | salt/engines/libvirt_events.py | _get_domain_event_detail | 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 | 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 | [
"def",
"_get_domain_event_detail",
"(",
"event",
",",
"detail",
")",
":",
"event_name",
"=",
"_get_libvirt_enum_string",
"(",
"'VIR_DOMAIN_EVENT_'",
",",
"event",
")",
"if",
"event_name",
"==",
"'unknown'",
":",
"return",
"event_name",
",",
"'unknown'",
"prefix",
... | Convert event and detail numeric values into a tuple of human readable strings | [
"Convert",
"event",
"and",
"detail",
"numeric",
"values",
"into",
"a",
"tuple",
"of",
"human",
"readable",
"strings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L178-L189 | train |
saltstack/salt | salt/engines/libvirt_events.py | _salt_send_event | 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) | 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) | [
"def",
"_salt_send_event",
"(",
"opaque",
",",
"conn",
",",
"data",
")",
":",
"tag_prefix",
"=",
"opaque",
"[",
"'prefix'",
"]",
"object_type",
"=",
"opaque",
"[",
"'object'",
"]",
"event_type",
"=",
"opaque",
"[",
"'event'",
"]",
"# Prepare the connection URI... | 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 | [
"Convenience",
"function",
"adding",
"common",
"data",
"to",
"the",
"event",
"and",
"sending",
"it",
"on",
"the",
"salt",
"event",
"bus",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L192-L231 | train |
saltstack/salt | salt/engines/libvirt_events.py | _salt_send_domain_event | 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) | 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) | [
"def",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"event",
",",
"event_data",
")",
":",
"data",
"=",
"{",
"'domain'",
":",
"{",
"'name'",
":",
"domain",
".",
"name",
"(",
")",
",",
"'id'",
":",
"domain",
".",
"ID",
"("... | 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 | [
"Helper",
"function",
"send",
"a",
"salt",
"event",
"for",
"a",
"libvirt",
"domain",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L234-L254 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_lifecycle_cb | 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
}) | 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
}) | [
"def",
"_domain_event_lifecycle_cb",
"(",
"conn",
",",
"domain",
",",
"event",
",",
"detail",
",",
"opaque",
")",
":",
"event_str",
",",
"detail_str",
"=",
"_get_domain_event_detail",
"(",
"event",
",",
"detail",
")",
"_salt_send_domain_event",
"(",
"opaque",
",... | Domain lifecycle events handler | [
"Domain",
"lifecycle",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L257-L266 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_rtc_change_cb | 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
}) | 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
}) | [
"def",
"_domain_event_rtc_change_cb",
"(",
"conn",
",",
"domain",
",",
"utcoffset",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'utcoffset'",
":",
"utcoffset",
... | Domain RTC change events handler | [
"Domain",
"RTC",
"change",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L276-L282 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_watchdog_cb | 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)
}) | 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)
}) | [
"def",
"_domain_event_watchdog_cb",
"(",
"conn",
",",
"domain",
",",
"action",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'action'",
":",
"_get_libvirt_enum_stri... | Domain watchdog events handler | [
"Domain",
"watchdog",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L285-L291 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_io_error_cb | 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
}) | 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
}) | [
"def",
"_domain_event_io_error_cb",
"(",
"conn",
",",
"domain",
",",
"srcpath",
",",
"devalias",
",",
"action",
",",
"reason",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
... | Domain I/O Error events handler | [
"Domain",
"I",
"/",
"O",
"Error",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L294-L303 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_graphics_cb | 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]
}) | 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]
}) | [
"def",
"_domain_event_graphics_cb",
"(",
"conn",
",",
"domain",
",",
"phase",
",",
"local",
",",
"remote",
",",
"auth",
",",
"subject",
",",
"opaque",
")",
":",
"prefix",
"=",
"'VIR_DOMAIN_EVENT_GRAPHICS_'",
"def",
"get_address",
"(",
"addr",
")",
":",
"'''\... | Domain graphics events handler | [
"Domain",
"graphics",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L306-L326 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_disk_change_cb | 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)
}) | 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)
}) | [
"def",
"_domain_event_disk_change_cb",
"(",
"conn",
",",
"domain",
",",
"old_src",
",",
"new_src",
",",
"dev",
",",
"reason",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
... | Domain disk change events handler | [
"Domain",
"disk",
"change",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L336-L345 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_tray_change_cb | 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)
}) | 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)
}) | [
"def",
"_domain_event_tray_change_cb",
"(",
"conn",
",",
"domain",
",",
"dev",
",",
"reason",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'dev'",
":",
"dev",
... | Domain tray change events handler | [
"Domain",
"tray",
"change",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L348-L355 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_pmwakeup_cb | 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
}) | 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
}) | [
"def",
"_domain_event_pmwakeup_cb",
"(",
"conn",
",",
"domain",
",",
"reason",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'reason'",
":",
"'unknown'",
"# curre... | Domain wakeup events handler | [
"Domain",
"wakeup",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L358-L364 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_pmsuspend_cb | 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
}) | 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
}) | [
"def",
"_domain_event_pmsuspend_cb",
"(",
"conn",
",",
"domain",
",",
"reason",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'reason'",
":",
"'unknown'",
"# curr... | Domain suspend events handler | [
"Domain",
"suspend",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L367-L373 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_balloon_change_cb | 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
}) | 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
}) | [
"def",
"_domain_event_balloon_change_cb",
"(",
"conn",
",",
"domain",
",",
"actual",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'actual'",
":",
"actual",
"}",
... | Domain balloon change events handler | [
"Domain",
"balloon",
"change",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L376-L382 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_pmsuspend_disk_cb | 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
}) | 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
}) | [
"def",
"_domain_event_pmsuspend_disk_cb",
"(",
"conn",
",",
"domain",
",",
"reason",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'reason'",
":",
"'unknown'",
"#... | Domain disk suspend events handler | [
"Domain",
"disk",
"suspend",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L385-L391 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_block_job_cb | 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)
}) | 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)
}) | [
"def",
"_domain_event_block_job_cb",
"(",
"conn",
",",
"domain",
",",
"disk",
",",
"job_type",
",",
"status",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'dis... | Domain block job events handler | [
"Domain",
"block",
"job",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L394-L402 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_device_removed_cb | 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
}) | 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
}) | [
"def",
"_domain_event_device_removed_cb",
"(",
"conn",
",",
"domain",
",",
"dev",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'dev'",
":",
"dev",
"}",
")"
] | Domain device removal events handler | [
"Domain",
"device",
"removal",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L405-L411 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_tunable_cb | def _domain_event_tunable_cb(conn, domain, params, opaque):
'''
Domain tunable events handler
'''
_salt_send_domain_event(opaque, conn, domain, opaque['event'], {
'params': params
}) | 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
}) | [
"def",
"_domain_event_tunable_cb",
"(",
"conn",
",",
"domain",
",",
"params",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'params'",
":",
"params",
"}",
")"
] | Domain tunable events handler | [
"Domain",
"tunable",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L414-L420 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_agent_lifecycle_cb | 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)
}) | 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)
}) | [
"def",
"_domain_event_agent_lifecycle_cb",
"(",
"conn",
",",
"domain",
",",
"state",
",",
"reason",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'state'",
":",
... | Domain agent lifecycle events handler | [
"Domain",
"agent",
"lifecycle",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L424-L431 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_device_added_cb | 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
}) | 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
}) | [
"def",
"_domain_event_device_added_cb",
"(",
"conn",
",",
"domain",
",",
"dev",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'dev'",
":",
"dev",
"}",
")"
] | Domain device addition events handler | [
"Domain",
"device",
"addition",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L434-L440 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_migration_iteration_cb | 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
}) | 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
}) | [
"def",
"_domain_event_migration_iteration_cb",
"(",
"conn",
",",
"domain",
",",
"iteration",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'iteration'",
":",
"itera... | Domain migration iteration events handler | [
"Domain",
"migration",
"iteration",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L444-L450 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_job_completed_cb | 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
}) | 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
}) | [
"def",
"_domain_event_job_completed_cb",
"(",
"conn",
",",
"domain",
",",
"params",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'params'",
":",
"params",
"}",
... | Domain job completion events handler | [
"Domain",
"job",
"completion",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L453-L459 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_device_removal_failed_cb | 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
}) | 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
}) | [
"def",
"_domain_event_device_removal_failed_cb",
"(",
"conn",
",",
"domain",
",",
"dev",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'dev'",
":",
"dev",
"}",
... | Domain device removal failure events handler | [
"Domain",
"device",
"removal",
"failure",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L462-L468 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_metadata_change_cb | 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
}) | 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
}) | [
"def",
"_domain_event_metadata_change_cb",
"(",
"conn",
",",
"domain",
",",
"mtype",
",",
"nsuri",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'type'",
":",
"... | Domain metadata change events handler | [
"Domain",
"metadata",
"change",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L471-L478 | train |
saltstack/salt | salt/engines/libvirt_events.py | _domain_event_block_threshold_cb | 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
}) | 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
}) | [
"def",
"_domain_event_block_threshold_cb",
"(",
"conn",
",",
"domain",
",",
"dev",
",",
"path",
",",
"threshold",
",",
"excess",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]"... | Domain block threshold events handler | [
"Domain",
"block",
"threshold",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L481-L490 | train |
saltstack/salt | salt/engines/libvirt_events.py | _network_event_lifecycle_cb | 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
}) | 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
}) | [
"def",
"_network_event_lifecycle_cb",
"(",
"conn",
",",
"net",
",",
"event",
",",
"detail",
",",
"opaque",
")",
":",
"_salt_send_event",
"(",
"opaque",
",",
"conn",
",",
"{",
"'network'",
":",
"{",
"'name'",
":",
"net",
".",
"name",
"(",
")",
",",
"'uu... | Network lifecycle events handler | [
"Network",
"lifecycle",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L493-L505 | train |
saltstack/salt | salt/engines/libvirt_events.py | _pool_event_lifecycle_cb | 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
}) | 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
}) | [
"def",
"_pool_event_lifecycle_cb",
"(",
"conn",
",",
"pool",
",",
"event",
",",
"detail",
",",
"opaque",
")",
":",
"_salt_send_event",
"(",
"opaque",
",",
"conn",
",",
"{",
"'pool'",
":",
"{",
"'name'",
":",
"pool",
".",
"name",
"(",
")",
",",
"'uuid'"... | Storage pool lifecycle events handler | [
"Storage",
"pool",
"lifecycle",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L508-L519 | train |
saltstack/salt | salt/engines/libvirt_events.py | _pool_event_refresh_cb | 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']
}) | 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']
}) | [
"def",
"_pool_event_refresh_cb",
"(",
"conn",
",",
"pool",
",",
"opaque",
")",
":",
"_salt_send_event",
"(",
"opaque",
",",
"conn",
",",
"{",
"'pool'",
":",
"{",
"'name'",
":",
"pool",
".",
"name",
"(",
")",
",",
"'uuid'",
":",
"pool",
".",
"UUIDString... | Storage pool refresh events handler | [
"Storage",
"pool",
"refresh",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L522-L532 | train |
saltstack/salt | salt/engines/libvirt_events.py | _nodedev_event_lifecycle_cb | 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
}) | 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
}) | [
"def",
"_nodedev_event_lifecycle_cb",
"(",
"conn",
",",
"dev",
",",
"event",
",",
"detail",
",",
"opaque",
")",
":",
"_salt_send_event",
"(",
"opaque",
",",
"conn",
",",
"{",
"'nodedev'",
":",
"{",
"'name'",
":",
"dev",
".",
"name",
"(",
")",
"}",
",",... | Node device lifecycle events handler | [
"Node",
"device",
"lifecycle",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L535-L545 | train |
saltstack/salt | salt/engines/libvirt_events.py | _nodedev_event_update_cb | 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']
}) | 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']
}) | [
"def",
"_nodedev_event_update_cb",
"(",
"conn",
",",
"dev",
",",
"opaque",
")",
":",
"_salt_send_event",
"(",
"opaque",
",",
"conn",
",",
"{",
"'nodedev'",
":",
"{",
"'name'",
":",
"dev",
".",
"name",
"(",
")",
"}",
",",
"'event'",
":",
"opaque",
"[",
... | Node device update events handler | [
"Node",
"device",
"update",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L548-L557 | train |
saltstack/salt | salt/engines/libvirt_events.py | _secret_event_lifecycle_cb | 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
}) | 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
}) | [
"def",
"_secret_event_lifecycle_cb",
"(",
"conn",
",",
"secret",
",",
"event",
",",
"detail",
",",
"opaque",
")",
":",
"_salt_send_event",
"(",
"opaque",
",",
"conn",
",",
"{",
"'secret'",
":",
"{",
"'uuid'",
":",
"secret",
".",
"UUIDString",
"(",
")",
"... | Secret lifecycle events handler | [
"Secret",
"lifecycle",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L560-L570 | train |
saltstack/salt | salt/engines/libvirt_events.py | _secret_event_value_changed_cb | 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']
}) | 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']
}) | [
"def",
"_secret_event_value_changed_cb",
"(",
"conn",
",",
"secret",
",",
"opaque",
")",
":",
"_salt_send_event",
"(",
"opaque",
",",
"conn",
",",
"{",
"'secret'",
":",
"{",
"'uuid'",
":",
"secret",
".",
"UUIDString",
"(",
")",
"}",
",",
"'event'",
":",
... | Secret value change events handler | [
"Secret",
"value",
"change",
"events",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L573-L582 | train |
saltstack/salt | salt/engines/libvirt_events.py | _callbacks_cleanup | 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) | 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) | [
"def",
"_callbacks_cleanup",
"(",
"cnx",
",",
"callback_ids",
")",
":",
"for",
"obj",
",",
"ids",
"in",
"callback_ids",
".",
"items",
"(",
")",
":",
"register_name",
"=",
"REGISTER_FUNCTIONS",
"[",
"obj",
"]",
"deregister_name",
"=",
"register_name",
".",
"r... | 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 | [
"Unregister",
"all",
"the",
"registered",
"callbacks"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L595-L608 | train |
saltstack/salt | salt/engines/libvirt_events.py | _register_callback | 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}) | 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}) | [
"def",
"_register_callback",
"(",
"cnx",
",",
"tag_prefix",
",",
"obj",
",",
"event",
",",
"real_id",
")",
":",
"libvirt_name",
"=",
"real_id",
"if",
"real_id",
"is",
"None",
":",
"libvirt_name",
"=",
"'VIR_{0}_EVENT_ID_{1}'",
".",
"format",
"(",
"obj",
",",... | 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 | [
"Helper",
"function",
"registering",
"a",
"callback"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L611-L643 | train |
saltstack/salt | salt/engines/libvirt_events.py | _append_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) | 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) | [
"def",
"_append_callback_id",
"(",
"ids",
",",
"obj",
",",
"callback_id",
")",
":",
"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 | [
"Helper",
"function",
"adding",
"a",
"callback",
"ID",
"to",
"the",
"IDs",
"dict",
".",
"The",
"callback",
"ids",
"dict",
"maps",
"an",
"object",
"to",
"event",
"callback",
"ids",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L646-L657 | train |
saltstack/salt | salt/engines/libvirt_events.py | start | 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) | 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) | [
"def",
"start",
"(",
"uri",
"=",
"None",
",",
"tag_prefix",
"=",
"'salt/engines/libvirt_events'",
",",
"filters",
"=",
"None",
")",
":",
"if",
"filters",
"is",
"None",
":",
"filters",
"=",
"[",
"'all'",
"]",
"try",
":",
"libvirt",
".",
"virEventRegisterDef... | 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' | [
"Listen",
"to",
"libvirt",
"events",
"and",
"forward",
"them",
"to",
"salt",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L660-L702 | train |
saltstack/salt | salt/modules/status.py | _number | 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 | 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 | [
"def",
"_number",
"(",
"text",
")",
":",
"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. | [
"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"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L59-L71 | train |
saltstack/salt | salt/modules/status.py | _get_boot_time_aix | 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 | 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 | [
"def",
"_get_boot_time_aix",
"(",
")",
":",
"boot_secs",
"=",
"0",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'ps -o etime= -p 1'",
")",
"if",
"res",
"[",
"'retcode'",
"]",
">",
"0",
":",
"raise",
"CommandExecutionError",
"(",
"'Unable to find bo... | 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 | [
"Return",
"the",
"number",
"of",
"seconds",
"since",
"boot",
"time",
"on",
"AIX"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L74-L94 | train |
saltstack/salt | salt/modules/status.py | _aix_loadavg | 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]} | 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]} | [
"def",
"_aix_loadavg",
"(",
")",
":",
"# 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",
"="... | Return the load average on AIX | [
"Return",
"the",
"load",
"average",
"on",
"AIX"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L97-L107 | train |
saltstack/salt | salt/modules/status.py | procs | 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 | 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 | [
"def",
"procs",
"(",
")",
":",
"# Get the user, pid and cmd",
"ret",
"=",
"{",
"}",
"uind",
"=",
"0",
"pind",
"=",
"0",
"cind",
"=",
"0",
"plines",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"__grains__",
"[",
"'ps'",
"]",
",",
"python_shell",
"=",
... | Return the process data
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.procs | [
"Return",
"the",
"process",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L118-L154 | train |
saltstack/salt | salt/modules/status.py | custom | 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 | 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 | [
"def",
"custom",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"conf",
"=",
"__salt__",
"[",
"'config.dot_vals'",
"]",
"(",
"'status'",
")",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"conf",
")",
":",
"func",
"=",
"'{0}()'",
".",
"format... | 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 | [
"Return",
"a",
"custom",
"composite",
"of",
"status",
"data",
"and",
"info",
"for",
"this",
"minion",
"based",
"on",
"the",
"minion",
"config",
"file",
".",
"An",
"example",
"config",
"like",
"might",
"be",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L157-L189 | train |
saltstack/salt | salt/modules/status.py | uptime | 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 | 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 | [
"def",
"uptime",
"(",
")",
":",
"curr_seconds",
"=",
"time",
".",
"time",
"(",
")",
"# Get uptime in seconds",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_linux",
"(",
")",
":",
"ut_path",
"=",
"\"/proc/uptime\"",
"if",
"not",
"os",
".",
"path"... | 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 | [
"Return",
"the",
"uptime",
"for",
"this",
"system",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L192-L265 | train |
saltstack/salt | salt/modules/status.py | loadavg | 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]} | 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]} | [
"def",
"loadavg",
"(",
")",
":",
"if",
"__grains__",
"[",
"'kernel'",
"]",
"==",
"'AIX'",
":",
"return",
"_aix_loadavg",
"(",
")",
"try",
":",
"load_avg",
"=",
"os",
".",
"getloadavg",
"(",
")",
"except",
"AttributeError",
":",
"# Some UNIX-based operating s... | 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 | [
"Return",
"the",
"load",
"averages",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L268-L293 | train |
saltstack/salt | salt/modules/status.py | cpustats | 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)() | 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)() | [
"def",
"cpustats",
"(",
")",
":",
"def",
"linux_cpustats",
"(",
")",
":",
"'''\n linux specific implementation of cpustats\n '''",
"ret",
"=",
"{",
"}",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/stat'",
",",... | 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 | [
"Return",
"the",
"CPU",
"stats",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L296-L441 | train |
saltstack/salt | salt/modules/status.py | meminfo | 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)() | 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)() | [
"def",
"meminfo",
"(",
")",
":",
"def",
"linux_meminfo",
"(",
")",
":",
"'''\n linux specific implementation of meminfo\n '''",
"ret",
"=",
"{",
"}",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/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 | [
"Return",
"the",
"memory",
"info",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L444-L604 | train |
saltstack/salt | salt/modules/status.py | cpuinfo | 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)() | 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)() | [
"def",
"cpuinfo",
"(",
")",
":",
"def",
"linux_cpuinfo",
"(",
")",
":",
"'''\n linux specific cpuinfo implementation\n '''",
"ret",
"=",
"{",
"}",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/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 | [
"..",
"versionchanged",
"::",
"2016",
".",
"3",
".",
"2",
"Return",
"the",
"CPU",
"info",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L607-L812 | train |
saltstack/salt | salt/modules/status.py | diskstats | 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)() | 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)() | [
"def",
"diskstats",
"(",
")",
":",
"def",
"linux_diskstats",
"(",
")",
":",
"'''\n linux specific implementation of diskstats\n '''",
"ret",
"=",
"{",
"}",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/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 | [
"..",
"versionchanged",
"::",
"2016",
".",
"3",
".",
"2",
"Return",
"the",
"disk",
"stats",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L815-L941 | train |
saltstack/salt | salt/modules/status.py | diskusage | 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 | 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 | [
"def",
"diskusage",
"(",
"*",
"args",
")",
":",
"selected",
"=",
"set",
"(",
")",
"fstypes",
"=",
"set",
"(",
")",
"if",
"not",
"args",
":",
"# select all filesystems",
"fstypes",
".",
"add",
"(",
"'*'",
")",
"else",
":",
"for",
"arg",
"in",
"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 | [
"Return",
"the",
"disk",
"usage",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L944-L1017 | train |
saltstack/salt | salt/modules/status.py | vmstats | 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)() | 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)() | [
"def",
"vmstats",
"(",
")",
":",
"def",
"linux_vmstats",
"(",
")",
":",
"'''\n linux specific implementation of vmstats\n '''",
"ret",
"=",
"{",
"}",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/vmstat'",
",",
... | .. 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 | [
"..",
"versionchanged",
"::",
"2016",
".",
"3",
".",
"2",
"Return",
"the",
"virtual",
"memory",
"stats",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1020-L1074 | train |
saltstack/salt | salt/modules/status.py | nproc | 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)() | 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)() | [
"def",
"nproc",
"(",
")",
":",
"def",
"linux_nproc",
"(",
")",
":",
"'''\n linux specific implementation of nproc\n '''",
"try",
":",
"return",
"_number",
"(",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'nproc'",
")",
".",
"strip",
"(",
")",
")",
"... | 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 | [
"Return",
"the",
"number",
"of",
"processing",
"units",
"available",
"on",
"this",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1077-L1123 | train |
saltstack/salt | salt/modules/status.py | netstats | 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)() | 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)() | [
"def",
"netstats",
"(",
")",
":",
"def",
"linux_netstats",
"(",
")",
":",
"'''\n linux specific netstats implementation\n '''",
"ret",
"=",
"{",
"}",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/net/netstat'",
... | 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 | [
"Return",
"the",
"network",
"stats",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1126-L1251 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.