text stringlengths 81 112k |
|---|
Creates or updates LXD profiles
name :
The name of the profile to create/update
description :
A description string
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privile... |
Ensure a LXD profile is not present, removing it if present.
name :
The name of the profile to remove.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/m... |
Returns a list of modules in loader.conf that load on boot.
def _get_persistent_modules():
'''
Returns a list of modules in loader.conf that load on boot.
'''
mods = set()
with salt.utils.files.fopen(_LOADER_CONF, 'r') as loader_conf:
for line in loader_conf:
line = salt.utils.s... |
Add a module to loader.conf to make it persistent.
def _set_persistent_module(mod):
'''
Add a module to loader.conf to make it persistent.
'''
if not mod or mod in mod_list(True) or mod not in \
available():
return set()
__salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(... |
Remove module from loader.conf. If comment is true only comment line where
module is.
def _remove_persistent_module(mod, comment):
'''
Remove module from loader.conf. If comment is true only comment line where
module is.
'''
if not mod or mod not in mod_list(True):
return set()
if ... |
Return a list of all available kernel modules
CLI Example:
.. code-block:: bash
salt '*' kmod.available
def available():
'''
Return a list of all available kernel modules
CLI Example:
.. code-block:: bash
salt '*' kmod.available
'''
ret = []
for path in __salt_... |
Return a dict containing information about currently loaded modules
CLI Example:
.. code-block:: bash
salt '*' kmod.lsmod
def lsmod():
'''
Return a dict containing information about currently loaded modules
CLI Example:
.. code-block:: bash
salt '*' kmod.lsmod
'''
... |
Return a list of the loaded module names
CLI Example:
.. code-block:: bash
salt '*' kmod.mod_list
def mod_list(only_persist=False):
'''
Return a list of the loaded module names
CLI Example:
.. code-block:: bash
salt '*' kmod.mod_list
'''
mods = set()
if only_pe... |
Load the specified kernel module
mod
Name of the module to add
persist
Write the module to sysrc kld_modules to make it load on system reboot
CLI Example:
.. code-block:: bash
salt '*' kmod.load bhyve
def load(mod, persist=False):
'''
Load the specified kernel modul... |
Remove the specified kernel module
mod
Name of module to remove
persist
Also remove module from /boot/loader.conf
comment
If persist is set don't remove line from /boot/loader.conf but only
comment it
CLI Example:
.. code-block:: bash
salt '*' kmod.remov... |
Returns requested Server Density authentication value from pillar.
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.get_sd_auth <val>
def get_sd_auth(val, sd_auth_pillar_name='serverdensity'):
'''
Returns requested Server Density authentication value from pillar.
CLI Exam... |
Pops out variables from params which starts with `variable_prefix`.
def _clean_salt_variables(params, variable_prefix="__"):
'''
Pops out variables from params which starts with `variable_prefix`.
'''
list(list(map(params.pop, [k for k in params if k.startswith(variable_prefix)])))
return params |
Function to create device in Server Density. For more info, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.create lama
salt '*' serverdensity_device.create rich_lama group=lama_... |
Delete a device from Server Density. For more information, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Deleting
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.delete 51f7eafcdba4bb235e000ae4
def delete(device_id):
'''
Delete a de... |
List devices in Server Density
Results will be filtered by any params passed to this function. For more
information, see the API docs on listing_ and searching_.
.. _listing: https://apidocs.serverdensity.com/Inventory/Devices/Listing
.. _searching: https://apidocs.serverdensity.com/Inventory/Devices/... |
Updates device information in Server Density. For more information see the
`API docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Updating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.update 51f7eafcdba4bb235e000ae4 name=lama group=lama_band
salt ... |
Function downloads Server Density installation agent, and installs sd-agent
with agent_key. Optionally the agent_version would select the series to
use (defaults on the v1 one).
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498
... |
Setup client and init datastore.
def _init_client():
'''Setup client and init datastore.
'''
global client, path_prefix
if client is not None:
return
etcd_kwargs = {
'host': __opts__.get('etcd.host', '127.0.0.1'),
'port': __opts__.get('etcd.port', 2379),
... |
Store a key value.
def store(bank, key, data):
'''
Store a key value.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
value = __context__['serial'].dumps(data)
client.write(etcd_key, base64.b64encode(value))
except Exception as exc:
ra... |
Fetch a key value.
def fetch(bank, key):
'''
Fetch a key value.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
value = client.read(etcd_key).value
return __context__['serial'].loads(base64.b64decode(value))
except etcd.EtcdKeyNotFound:
... |
Remove the key from the cache bank with all the key content.
def flush(bank, key=None):
'''
Remove the key from the cache bank with all the key content.
'''
_init_client()
if key is None:
etcd_key = '{0}/{1}'.format(path_prefix, bank)
else:
etcd_key = '{0}/{1}/{2}'.format(path_p... |
Recursively walk dirs. Return flattened list of keys.
r: etcd.EtcdResult
def _walk(r):
'''
Recursively walk dirs. Return flattened list of keys.
r: etcd.EtcdResult
'''
if not r.dir:
return [r.key.split('/', 3)[3]]
keys = []
for c in client.read(r.key).children:
keys.ext... |
Return an iterable object containing all entries stored in the specified
bank.
def ls(bank):
'''
Return an iterable object containing all entries stored in the specified
bank.
'''
_init_client()
path = '{0}/{1}'.format(path_prefix, bank)
try:
return _walk(client.read(path))
... |
Checks if the specified bank contains the specified key.
def contains(bank, key):
'''
Checks if the specified bank contains the specified key.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
r = client.read(etcd_key)
# return True for keys, not di... |
Parse the info returned by udevadm command.
def _parse_udevadm_info(udev_info):
'''
Parse the info returned by udevadm command.
'''
devices = []
dev = {}
for line in (line.strip() for line in udev_info.splitlines()):
if line:
line = line.split(':', 1)
if len(lin... |
Replace list with only one element to the value of the element.
:param dev:
:return:
def _normalize_info(dev):
'''
Replace list with only one element to the value of the element.
:param dev:
:return:
'''
for sect, val in dev.items():
if len(val) == 1:
dev[sect] = v... |
Extract all info delivered by udevadm
CLI Example:
.. code-block:: bash
salt '*' udev.info /dev/sda
salt '*' udev.info /sys/class/net/eth0
def info(dev):
'''
Extract all info delivered by udevadm
CLI Example:
.. code-block:: bash
salt '*' udev.info /dev/sda
... |
Return all the udev database
CLI Example:
.. code-block:: bash
salt '*' udev.exportdb
def exportdb():
'''
Return all the udev database
CLI Example:
.. code-block:: bash
salt '*' udev.exportdb
'''
cmd = 'udevadm info --export-db'
udev_result = __salt__['cmd.run... |
Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
:raises: SaltInvocationError on Invalid Date/Time string
def _get_date_time_format(dt_string):
'''
Function that detects ... |
Displays the current date
:return: the system date
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_date
def get_date():
'''
Displays the current date
:return: the system date
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timez... |
Set the current month, day, and year
:param str date: The date to set. Valid date formats are:
- %m:%d:%y
- %m:%d:%Y
- %m/%d/%y
- %m/%d/%Y
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Date format
:raises: CommandEx... |
Get the current system time.
:return: The current time in 24 hour format
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time
def get_time():
'''
Get the current system time.
:return: The current time in 24 hour format
:rtype: str
CLI Example:
... |
Sets the current time. Must be in 24 hour format.
:param str time: The time to set in 24 hour format. The value must be
double quoted. ie: '"17:46"'
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Time format
:raises: CommandExecutionError o... |
Displays the current time zone
:return: The current time zone
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone
def get_zone():
'''
Displays the current time zone
:return: The current time zone
:rtype: str
CLI Example:
.. code-block:: bash
... |
Displays a list of available time zones. Use this list when setting a
time zone using ``timezone.set_zone``
:return: a list of time zones
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' timezone.list_zones
def list_zones():
'''
Displays a list of available time zones. Us... |
Set the local time zone. Use ``timezone.list_zones`` to list valid time_zone
arguments
:param str time_zone: The time zone to apply
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Timezone
:raises: CommandExecutionError on failure
CLI Exampl... |
Display whether network time is on or off
:return: True if network time is on, False if off
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' timezone.get_using_network_time
def get_using_network_time():
'''
Display whether network time is on or off
:return: True if netwo... |
Set whether network time is on or off.
:param enable: True to enable, False to disable. Can also use 'on' or 'off'
:type: str bool
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezon... |
Display the currently set network time server.
:return: the network time server
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time_server
def get_time_server():
'''
Display the currently set network time server.
:return: the network time server
:rtype:... |
Designates a network time server. Enter the IP address or DNS name for the
network time server.
:param time_server: IP or DNS name of the network time server. If nothing
is passed the time server will be set to the macOS default of
'time.apple.com'
:type: str
:return: True if successfu... |
Gets snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the ar... |
Gets the specific version string of a snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id... |
Get a value from the dictionary
def get(key, profile=None): # pylint: disable=W0613
'''
Get a value from the dictionary
'''
data = _get_values(profile)
# Decrypt SDB data if specified in the profile
if profile and profile.get('gpg', False):
return salt.utils.data.traverse_dict_and_lis... |
Retrieve all the referenced files, deserialize, then merge them together
def _get_values(profile=None):
'''
Retrieve all the referenced files, deserialize, then merge them together
'''
profile = profile or {}
serializers = salt.loader.serializers(__opts__)
ret = {}
for fname in profile.get... |
Ensures that the host exists, eventually creates new host.
NOTE: please use argument visible_name instead of name to not mess with name from salt sls. This function accepts
all standard host properties: keyword argument names differ depending on your zabbix version, see:
https://www.zabbix.com/documentation... |
Ensures that the host does not exists, eventually deletes host.
.. versionadded:: 2016.3.0
:param: name: technical name of the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can a... |
Ensures that templates are assigned to the host.
.. versionadded:: 2017.7.0
:param host: technical name of the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in op... |
This function gets called when the proxy starts up.
def init(opts):
'''
This function gets called when the proxy starts up.
'''
if 'host' not in opts['proxy']:
log.critical('No \'host\' key found in pillar for this proxy.')
return False
if 'username' not in opts['proxy']:
lo... |
The configConfMo method configures the specified managed object in a single subtree (for example, DN).
def set_config_modify(dn=None, inconfig=None, hierarchical=False):
'''
The configConfMo method configures the specified managed object in a single subtree (for example, DN).
'''
ret = {}
cookie = ... |
Logs into the cimc device and returns the session cookie.
def logon():
'''
Logs into the cimc device and returns the session cookie.
'''
content = {}
payload = "<aaaLogin inName='{0}' inPassword='{1}'></aaaLogin>".format(DETAILS['username'], DETAILS['password'])
r = __utils__['http.query'](DETA... |
Closes the session with the device.
def logout(cookie=None):
'''
Closes the session with the device.
'''
payload = '<aaaLogout cookie="{0}" inCookie="{0}"></aaaLogout>'.format(cookie)
__utils__['http.query'](DETAILS['url'],
data=payload,
metho... |
Converts the etree to dict
def prepare_return(x):
'''
Converts the etree to dict
'''
ret = {}
for a in list(x):
if a.tag not in ret:
ret[a.tag] = []
ret[a.tag].append(prepare_return(a))
for a in x.attrib:
ret[a] = x.attrib[a]
return ret |
Get the grains from the proxied device
def grains():
'''
Get the grains from the proxied device
'''
if not DETAILS.get('grains_cache', {}):
DETAILS['grains_cache'] = GRAINS_CACHE
try:
compute_rack = get_config_resolver_class('computeRackUnit', False)
DETAILS['gra... |
Returns true if the device is reachable, else false.
def ping():
'''
Returns true if the device is reachable, else false.
'''
try:
cookie = logon()
logout(cookie)
except salt.exceptions.CommandExecutionError:
return False
except Exception as err:
log.debug(err)
... |
Guess an archive type (tar, zip, or rar) by its file extension
def guess_archive_type(name):
'''
Guess an archive type (tar, zip, or rar) by its file extension
'''
name = name.lower()
for ending in ('tar', 'tar.gz', 'tgz',
'tar.bz2', 'tbz2', 'tbz',
'tar.xz', 't... |
Helper function which does exactly what ``tempfile.mkstemp()`` does but
accepts another argument, ``close_fd``, which, by default, is true and closes
the fd before returning the file path. Something commonly done throughout
Salt's code.
def mkstemp(*args, **kwargs):
'''
Helper function which does e... |
Recursively copy the source directory to the destination,
leaving files with the source does not explicitly overwrite.
(identical to cp -r on a unix machine)
def recursive_copy(source, dest):
'''
Recursively copy the source directory to the destination,
leaving files with the source does not expli... |
Copy files from a source to a destination in an atomic way, and if
specified cache the file.
def copyfile(source, dest, backup_mode='', cachedir=''):
'''
Copy files from a source to a destination in an atomic way, and if
specified cache the file.
'''
if not os.path.isfile(source):
raise... |
On Windows, os.rename() will fail with a WindowsError exception if a file
exists at the destination path. This function checks for this error and if
found, it deletes the destination path first.
def rename(src, dst):
'''
On Windows, os.rename() will fail with a WindowsError exception if a file
exis... |
Common code for raising exceptions when reading a file fails
The ignore argument can be an iterable of integer error codes (or a single
integer error code) that should be ignored.
def process_read_exception(exc, path, ignore=None):
'''
Common code for raising exceptions when reading a file fails
... |
Obtain a write lock. If one exists, wait for it to release first
def wait_lock(path, lock_fn=None, timeout=5, sleep=0.1, time_start=None):
'''
Obtain a write lock. If one exists, wait for it to release first
'''
if not isinstance(path, six.string_types):
raise FileLockError('path must be a stri... |
Temporarily set the umask and restore once the contextmanager exits
def set_umask(mask):
'''
Temporarily set the umask and restore once the contextmanager exits
'''
if mask is None or salt.utils.platform.is_windows():
# Don't attempt on Windows, or if no mask was passed
yield
else:
... |
Wrapper around open() built-in to set CLOEXEC on the fd.
This flag specifies that the file descriptor should be closed when an exec
function is invoked;
When a file descriptor is allocated (as with open or dup), this bit is
initially cleared on the new file descriptor, meaning that descriptor will
... |
Shortcut for fopen with lock and context manager.
def flopen(*args, **kwargs):
'''
Shortcut for fopen with lock and context manager.
'''
filename, args = args[0], args[1:]
writing = 'wa'
with fopen(filename, *args, **kwargs) as f_handle:
try:
if is_fcntl_available(check_suno... |
Shortcut for fopen with extra uid, gid, and mode options.
Supported optional Keyword Arguments:
mode
Explicit mode to set. Mode is anything os.chmod would accept
as input for mode. Works only on unix/unix-like systems.
uid
The uid to set, if not set, or it is None or -1 no changes... |
A clone of the python os.walk function with some checks for recursive
symlinks. Unlike os.walk this follows symlinks by default.
def safe_walk(top, topdown=True, onerror=None, followlinks=True, _seen=None):
'''
A clone of the python os.walk function with some checks for recursive
symlinks. Unlike os.wa... |
Platform-independent recursive delete. Includes code from
http://stackoverflow.com/a/2656405
def rm_rf(path):
'''
Platform-independent recursive delete. Includes code from
http://stackoverflow.com/a/2656405
'''
def _onerror(func, path, exc_info):
'''
Error handler for `shutil.rm... |
Simple function to check if the ``fcntl`` module is available or not.
If ``check_sunos`` is passed as ``True`` an additional check to see if host is
SunOS is also made. For additional information see: http://goo.gl/159FF8
def is_fcntl_available(check_sunos=False):
'''
Simple function to check if the `... |
Input the basename of a file, without the directory tree, and returns a safe name to use
i.e. only the required characters are converted by urllib.quote
If the input is a PY2 String, output a PY2 String. If input is Unicode output Unicode.
For consistency all platforms are treated the same. Hard coded to ut... |
Input the full path and filename, splits on directory separator and calls safe_filename_leaf for
each part of the path. dir_sep allows coder to force a directory separate to a particular character
.. versionadded:: 2017.7.2
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
def safe_filepath(fil... |
Uses heuristics to guess whether the given file is text or binary,
by reading a single block of bytes from the file.
If more than 30% of the chars in the block are non-text, or there
are NUL ('\x00') bytes in the block, assume this is a binary file.
def is_text(fp_, blocksize=512):
'''
Uses heurist... |
Detects if the file is a binary, returns bool. Returns True if the file is
a bin, False if the file is not and None if the file is not available.
def is_binary(path):
'''
Detects if the file is a binary, returns bool. Returns True if the file is
a bin, False if the file is not and None if the file is n... |
Runs os.remove(path) and suppresses the OSError if the file doesn't exist
def remove(path):
'''
Runs os.remove(path) and suppresses the OSError if the file doesn't exist
'''
try:
os.remove(path)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise |
Return a list of all files found under directory (and its subdirectories)
def list_files(directory):
'''
Return a list of all files found under directory (and its subdirectories)
'''
ret = set()
ret.add(directory)
for root, dirs, files in safe_walk(directory):
for name in files:
... |
Return a mode value, normalized to a string and containing a leading zero
if it does not have one.
Allow "keep" as a valid mode (used by file state/module to preserve mode
from the Salt fileserver in file states).
def normalize_mode(mode):
'''
Return a mode value, normalized to a string and contai... |
Convert human-readable units to bytes
def human_size_to_bytes(human_size):
'''
Convert human-readable units to bytes
'''
size_exp_map = {'K': 1, 'M': 2, 'G': 3, 'T': 4, 'P': 5}
human_size_str = six.text_type(human_size)
match = re.match(r'^(\d+)([KMGTP])?$', human_size_str)
if not match:
... |
Backup a file on the minion
def backup_minion(path, bkroot):
'''
Backup a file on the minion
'''
dname, bname = os.path.split(path)
if salt.utils.platform.is_windows():
src_dir = dname.replace(':', '_')
else:
src_dir = dname[1:]
if not salt.utils.platform.is_windows():
... |
Detect a file's encoding using the following:
- Check for Byte Order Marks (BOM)
- Check for UTF-8 Markers
- Check System Encoding
- Check for ascii
Args:
path (str): The path to the file to check
Returns:
str: The encoding of the file
Raises:
CommandExecutionErro... |
Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
orgname
Name of the organization in which the dashboard should be present.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
def absent(name, orgna... |
Provide grains about zpools
def _zfs_pool_data():
'''
Provide grains about zpools
'''
grains = {}
# collect zpool data
zpool_list_cmd = __utils__['zfs.zpool_command'](
'list',
flags=['-H'],
opts={'-o': 'name,size'},
)
for zpool in __salt__['cmd.run'](zpool_list_... |
Provide grains for zfs/zpool
def zfs():
'''
Provide grains for zfs/zpool
'''
grains = {}
grains['zfs_support'] = __utils__['zfs.is_supported']()
grains['zfs_feature_flags'] = __utils__['zfs.has_feature_flags']()
if grains['zfs_support']:
grains = salt.utils.dictupdate.update(grains,... |
Send a "Magic Packet" to wake up a list of Minions.
This list must contain one MAC hardware address per line
CLI Example:
.. code-block:: bash
salt-run network.wollist '/path/to/maclist'
salt-run network.wollist '/path/to/maclist' 255.255.255.255 7
salt-run network.wollist '/path/... |
Send a "Magic Packet" to wake up a Minion
CLI Example:
.. code-block:: bash
salt-run network.wol 08-00-27-13-69-77
salt-run network.wol 080027136977 255.255.255.255 7
salt-run network.wol 08:00:27:13:69:77 255.255.255.255 7
def wol(mac, bcast='255.255.255.255', destport=9):
'''
... |
Send a "Magic Packet" to wake up Minions that are matched in the grains cache
CLI Example:
.. code-block:: bash
salt-run network.wolmatch minion_id
salt-run network.wolmatch 192.168.0.0/16 tgt_type='ipcidr' bcast=255.255.255.255 destport=7
def wolmatch(tgt, tgt_type='glob', bcast='255.255.25... |
Return a conn object for accessing memcached
def get_conn(opts, profile=None, host=None, port=None):
'''
Return a conn object for accessing memcached
'''
if not (host and port):
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
... |
Set a key on the memcached server, overwriting the value if it exists.
def set_(conn,
key,
value,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Set a key on the memcached server, overwriting the value if it exists.
'''
if not isinstance(time, int... |
Returns the HTTP auth header
def _get_auth(username, password):
'''
Returns the HTTP auth header
'''
if username and password:
return requests.auth.HTTPBasicAuth(username, password)
else:
return None |
Returns the URL of the endpoint
def _get_url(ssl, url, port, path):
'''
Returns the URL of the endpoint
'''
if ssl:
return 'https://{0}:{1}/management/domain/{2}'.format(url, port, path)
else:
return 'http://{0}:{1}/management/domain/{2}'.format(url, port, path) |
Removes SaltStack params from **kwargs
def _clean_data(data):
'''
Removes SaltStack params from **kwargs
'''
for key in list(data):
if key.startswith('__pub'):
del data[key]
return data |
Check response status code + success_code returned by glassfish
def _api_response(response):
'''
Check response status code + success_code returned by glassfish
'''
if response.status_code == 404:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionErr... |
Do a GET request to the API
def _api_get(path, server=None):
'''
Do a GET request to the API
'''
server = _get_server(server)
response = requests.get(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['password']),
... |
Do a POST request to the API
def _api_post(path, data, server=None):
'''
Do a POST request to the API
'''
server = _get_server(server)
response = requests.post(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['password'... |
Do a DELETE request to the API
def _api_delete(path, data, server=None):
'''
Do a DELETE request to the API
'''
server = _get_server(server)
response = requests.delete(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['p... |
Enum elements
def _enum_elements(name, server=None):
'''
Enum elements
'''
elements = []
data = _api_get(name, server)
if any(data['extraProperties']['childResources']):
for element in data['extraProperties']['childResources']:
elements.append(element)
return elemen... |
Get an element's properties
def _get_element_properties(name, element_type, server=None):
'''
Get an element's properties
'''
properties = {}
data = _api_get('{0}/{1}/property'.format(element_type, name), server)
# Get properties into a dict
if any(data['extraProperties']['properties']):
... |
Get an element with or without properties
def _get_element(name, element_type, server=None, with_properties=True):
'''
Get an element with or without properties
'''
element = {}
name = quote(name, safe='')
data = _api_get('{0}/{1}'.format(element_type, name), server)
# Format data, get pro... |
Create a new element
def _create_element(name, element_type, data, server=None):
'''
Create a new element
'''
# Define property and id from name and properties + remove SaltStack parameters
if 'properties' in data:
data['property'] = ''
for key, value in data['properties'].items():
... |
Update an element, including it's properties
def _update_element(name, element_type, data, server=None):
'''
Update an element, including it's properties
'''
# Urlencode the name (names may have slashes)
name = quote(name, safe='')
# Update properties first
if 'properties' in data:
... |
Delete an element
def _delete_element(name, element_type, data, server=None):
'''
Delete an element
'''
_api_delete('{0}/{1}'.format(element_type, quote(name, safe='')), data, server)
return name |
Create a connection pool
def create_connector_c_pool(name, server=None, **kwargs):
'''
Create a connection pool
'''
defaults = {
'connectionDefinitionName': 'javax.jms.ConnectionFactory',
'resourceAdapterName': 'jmsra',
'associateWithThread': False,
'connectionCreationRe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.