INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
r Remove all triggers from the task.
def clear_triggers(name, location='\\'): r''' Remove all triggers from the task. :param str name: The name of the task from which to clear all triggers. :param str location: A string value representing the location of the task. Default is '\\' which is the root for the task scheduler (...
Get a connection to CouchDB
def _get_conn(profile): ''' Get a connection to CouchDB ''' DEFAULT_BASE_URL = _construct_uri(profile) or 'http://localhost:5984' server = couchdb.Server() if profile['database'] not in server: server.create(profile['database']) return server
Set a key/ value pair in couchdb
def set_(key, value, profile=None): ''' Set a key/value pair in couchdb ''' db = _get_db(profile) return db.save({'_id': uuid4().hex, key: value})
Generate a key for use with salt - ssh
def gen_key(path): ''' Generate a key for use with salt-ssh ''' cmd = 'ssh-keygen -P "" -f {0} -t rsa -q'.format(path) if not os.path.isdir(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) subprocess.call(cmd, shell=True)
Return the correct shell interface for the target system
def gen_shell(opts, **kwargs): ''' Return the correct shell interface for the target system ''' if kwargs['winrm']: try: import saltwinshell shell = saltwinshell.Shell(opts, **kwargs) except ImportError: log.error('The saltwinshell library is not avail...
Parse out an error and return a targeted error string
def get_error(self, errstr): ''' Parse out an error and return a targeted error string ''' for line in errstr.split('\n'): if line.startswith('ssh:'): return line if line.startswith('Pseudo-terminal'): continue if 'to th...
Return options for the ssh command base for Salt to call
def _key_opts(self): ''' Return options for the ssh command base for Salt to call ''' options = [ 'KbdInteractiveAuthentication=no', ] if self.passwd: options.append('PasswordAuthentication=yes') else: options....
Return options to pass to ssh
def _passwd_opts(self): ''' Return options to pass to ssh ''' # TODO ControlMaster does not work without ControlPath # user could take advantage of it if they set ControlPath in their # ssh config. Also, ControlPersist not widely available. options = ['ControlMas...
Return the string to execute ssh - copy - id
def _copy_id_str_old(self): ''' Return the string to execute ssh-copy-id ''' if self.passwd: # Using single quotes prevents shell expansion and # passwords containing '$' return "{0} {1} '{2} -p {3} {4} {5}@{6}'".format( 'ssh-copy-i...
Execute ssh - copy - id to plant the id file on the target
def copy_id(self): ''' Execute ssh-copy-id to plant the id file on the target ''' stdout, stderr, retcode = self._run_cmd(self._copy_id_str_old()) if salt.defaults.exitcodes.EX_OK != retcode and 'Usage' in stderr: stdout, stderr, retcode = self._run_cmd(self._copy_id_...
Return the cmd string to execute
def _cmd_str(self, cmd, ssh='ssh'): ''' Return the cmd string to execute ''' # TODO: if tty, then our SSH_SHIM cannot be supplied from STDIN Will # need to deliver the SHIM to the remote host and execute it there command = [ssh] if ssh != 'scp': comm...
Cleanly execute the command string
def _old_run_cmd(self, cmd): ''' Cleanly execute the command string ''' try: proc = subprocess.Popen( cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, ) data = proc.commun...
cmd iterator
def _run_nb_cmd(self, cmd): ''' cmd iterator ''' try: proc = salt.utils.nb_popen.NonBlockingPopen( cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, ) while True: ...
Yield None until cmd finished
def exec_nb_cmd(self, cmd): ''' Yield None until cmd finished ''' r_out = [] r_err = [] rcode = None cmd = self._cmd_str(cmd) logmsg = 'Executing non-blocking command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passw...
Execute a remote command
def exec_cmd(self, cmd): ''' Execute a remote command ''' cmd = self._cmd_str(cmd) logmsg = 'Executing command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, ('*' * 6)) if 'decode("base64")' in logmsg or 'base64.b64decode(' in ...
scp a file or files to a remote system
def send(self, local, remote, makedirs=False): ''' scp a file or files to a remote system ''' if makedirs: self.exec_cmd('mkdir -p {0}'.format(os.path.dirname(remote))) # scp needs [<ipv6} host = self.host if ':' in host: host = '[{0}]'.fo...
Execute a shell command via VT. This is blocking and assumes that ssh is being run
def _run_cmd(self, cmd, key_accept=False, passwd_retries=3): ''' Execute a shell command via VT. This is blocking and assumes that ssh is being run ''' if not cmd: return '', 'No command or passphrase', 245 term = salt.utils.vt.Terminal( cmd, ...
sets up the sentry handler
def setup_handlers(): ''' sets up the sentry handler ''' __grains__ = salt.loader.grains(__opts__) __salt__ = salt.loader.minion_mods(__opts__) if 'sentry_handler' not in __opts__: log.debug('No \'sentry_handler\' key was found in the configuration') return False options = {}...
Return a value for name from master config file options or defaults.
def _config(key, mandatory=True, opts=None): ''' Return a value for 'name' from master config file options or defaults. ''' try: if opts: value = opts['auth.ldap.{0}'.format(key)] else: value = __opts__['auth.ldap.{0}'.format(key)] except KeyError: try...
Render config template substituting username where found.
def _render_template(param, username): ''' Render config template, substituting username where found. ''' env = Environment() template = env.from_string(param) variables = {'username': username} return template.render(variables)
Bind with binddn and bindpw only for searching LDAP: param anonymous: Try binding anonymously: param opts: Pass in when __opts__ is not available: return: LDAPConnection object
def _bind_for_search(anonymous=False, opts=None): ''' Bind with binddn and bindpw only for searching LDAP :param anonymous: Try binding anonymously :param opts: Pass in when __opts__ is not available :return: LDAPConnection object ''' # Get config params; create connection dictionary con...
Authenticate via an LDAP bind
def _bind(username, password, anonymous=False, opts=None): ''' Authenticate via an LDAP bind ''' # Get config params; create connection dictionary basedn = _config('basedn', opts=opts) scope = _config('scope', opts=opts) connargs = {} # config params (auth.ldap.*) params = { ...
Simple LDAP auth
def auth(username, password): ''' Simple LDAP auth ''' if not HAS_LDAP: log.error('LDAP authentication requires python-ldap module') return False bind = None # If bind credentials are configured, verify that we receive a valid bind if _config('binddn', mandatory=False) and ...
Authenticate against an LDAP group
def groups(username, **kwargs): ''' Authenticate against an LDAP group Behavior is highly dependent on if Active Directory is in use. AD handles group membership very differently than OpenLDAP. See the :ref:`External Authentication <acl-eauth>` documentation for a thorough discussion of availa...
Query LDAP retrieve list of minion_ids from an OU or other search. For each minion_id returned from the LDAP search copy the perms matchers into the auth dictionary: param auth_list:: param opts: __opts__ for when __opts__ is not injected: return: Modified auth list.
def process_acl(auth_list, opts=None): ''' Query LDAP, retrieve list of minion_ids from an OU or other search. For each minion_id returned from the LDAP search, copy the perms matchers into the auth dictionary :param auth_list: :param opts: __opts__ for when __opts__ is not injected :return:...
Check for Netmiko arguments that were passed in as NAPALM optional arguments.
def _get_netmiko_args(optional_args): ''' Check for Netmiko arguments that were passed in as NAPALM optional arguments. Return a dictionary of these optional args that will be passed into the Netmiko ConnectHandler call. .. note:: This is a port of the NAPALM helper for backwards compatib...
Reconnect the NAPALM proxy when the connection is dropped by the network device. The connection can be forced to be restarted using the force argument.
def reconnect(force=False, **kwargs): # pylint: disable=unused-argument ''' Reconnect the NAPALM proxy when the connection is dropped by the network device. The connection can be forced to be restarted using the ``force`` argument. .. note:: This function can be used only when running...
Execute arbitrary methods from the NAPALM library. To see the expected output please consult the NAPALM documentation.
def call(method, *args, **kwargs): ''' Execute arbitrary methods from the NAPALM library. To see the expected output, please consult the NAPALM documentation. .. note:: This feature is not recommended to be used in production. It should be used for testing only! CLI Example: ...
Return the compliance report.
def compliance_report(filepath=None, string=None, renderer='jinja|yaml', **kwargs): ''' Return the compliance report. filepath The absolute path to the validation file. .. versionchanged:: 2019.2.0 Beginning with re...
.. versionadded:: 2019. 2. 0
def netmiko_args(**kwargs): ''' .. versionadded:: 2019.2.0 Return the key-value arguments used for the authentication arguments for the netmiko module. When running in a non-native NAPALM driver (e.g., ``panos``, `f5``, ``mos`` - either from https://github.com/napalm-automation-community or de...
.. versionadded:: 2019. 2. 0
def netmiko_fun(fun, *args, **kwargs): ''' .. versionadded:: 2019.2.0 Call an arbitrary function from the :mod:`Netmiko<salt.modules.netmiko_mod>` module, passing the authentication details from the existing NAPALM connection. fun The name of the function from the :mod:`Netmiko<salt.mo...
.. versionadded:: 2019. 2. 0
def netmiko_call(method, *args, **kwargs): ''' .. versionadded:: 2019.2.0 Execute an arbitrary Netmiko method, passing the authentication details from the existing NAPALM connection. method The name of the Netmiko method to execute. args List of arguments to send to the Netmik...
.. versionadded:: 2019. 2. 0
def netmiko_multi_call(*methods, **kwargs): ''' .. versionadded:: 2019.2.0 Execute a list of arbitrary Netmiko methods, passing the authentication details from the existing NAPALM connection. methods List of dictionaries with the following keys: - ``name``: the name of the Netmiko...
.. versionadded:: 2019. 2. 0
def netmiko_commands(*commands, **kwargs): ''' .. versionadded:: 2019.2.0 Invoke one or more commands to be executed on the remote device, via Netmiko. Returns a list of strings, with the output from each command. commands A list of commands to be executed. expect_string Regul...
.. versionadded:: 2019. 2. 0
def netmiko_config(*config_commands, **kwargs): ''' .. versionadded:: 2019.2.0 Load a list of configuration commands on the remote device, via Netmiko. .. warning:: Please remember that ``netmiko`` does not have any rollback safeguards and any configuration change will be directly loa...
.. versionadded:: 2019. 2. 0
def junos_rpc(cmd=None, dest=None, format=None, **kwargs): ''' .. versionadded:: 2019.2.0 Execute an RPC request on the remote Junos device. cmd The RPC request to the executed. To determine the RPC request, you can check the from the command line of the device, by executing the usual ...
.. versionadded:: 2019. 2. 0
def junos_install_os(path=None, **kwargs): ''' .. versionadded:: 2019.2.0 Installs the given image on the device. path The image file source. This argument supports the following URIs: - Absolute path on the Minion. - ``salt://`` to fetch from the Salt fileserver. - ``...
.. versionadded:: 2019. 2. 0
def junos_facts(**kwargs): ''' .. versionadded:: 2019.2.0 The complete list of Junos facts collected by ``junos-eznc``. CLI Example: .. code-block:: bash salt '*' napalm.junos_facts ''' prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable if not prep['r...
.. versionadded:: 2019. 2. 0
def junos_cli(command, format=None, dev_timeout=None, dest=None, **kwargs): ''' .. versionadded:: 2019.2.0 Execute a CLI command and return the output in the specified format. command The command to execute on the Junos CLI. format: ``text`` Format in which to get the CLI output (...
.. versionadded:: 2019. 2. 0
def junos_copy_file(src, dst, **kwargs): ''' .. versionadded:: 2019.2.0 Copies the file on the remote Junos device. src The source file path. This argument accepts the usual Salt URIs (e.g., ``salt://``, ``http://``, ``https://``, ``s3://``, ``ftp://``, etc.). dst The dest...
.. versionadded:: 2019. 2. 0
def junos_call(fun, *args, **kwargs): ''' .. versionadded:: 2019.2.0 Execute an arbitrary function from the :mod:`junos execution module <salt.module.junos>`. To check what ``args`` and ``kwargs`` you must send to the function, please consult the appropriate documentation. fun The ...
.. versionadded:: 2019. 2. 0
def pyeapi_nxos_api_args(**prev_kwargs): ''' .. versionadded:: 2019.2.0 Return the key-value arguments used for the authentication arguments for the :mod:`pyeapi execution module <salt.module.arista_pyeapi>`. CLI Example: .. code-block:: bash salt '*' napalm.pyeapi_nxos_api_args ...
.. versionadded:: 2019. 2. 0
def pyeapi_call(method, *args, **kwargs): ''' .. versionadded:: 2019.2.0 Invoke an arbitrary method from the ``pyeapi`` library. This function forwards the existing connection details to the :mod:`pyeapi.run_commands <salt.module.arista_pyeapi.run_commands>` execution function. method ...
.. versionadded:: 2019. 2. 0
def pyeapi_config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' .. versionadded:: 2019.2.0 Configures the Arista switch with th...
.. versionadded:: 2019. 2. 0
def nxos_api_rpc(commands, method='cli', **kwargs): ''' .. versionadded:: 2019.2.0 Execute an arbitrary RPC request via the Nexus API. commands The RPC commands to be executed. method: ``cli`` The type of the response, i.e., raw text (``cli_ascii`...
.. versionadded:: 2019. 2. 0
def nxos_api_config(commands=None, config_file=None, template_engine='jinja', context=None, defaults=None, saltenv='base', **kwargs): ''' .. versionadded:: 2019.2.0 Configures the Nexus ...
.. versionadded:: 2019. 2. 0
def nxos_api_show(commands, raw_text=True, **kwargs): ''' .. versionadded:: 2019.2.0 Execute one or more show (non-configuration) commands. commands The commands to be executed. raw_text: ``True`` Whether to return raw text or structured data. CLI Example: .. code-block:...
.. versionadded:: 2019. 2. 0
def rpc(command, **kwargs): ''' .. versionadded:: 2019.2.0 This is a wrapper to execute RPC requests on various network operating systems supported by NAPALM, invoking the following functions for the NAPALM native drivers: - :py:func:`napalm.junos_rpc <salt.modules.napalm_mod.junos_rpc>` for `...
r.. versionadded:: 2019. 2. 0
def config_find_lines(regex, source='running'): r''' .. versionadded:: 2019.2.0 Return the configuration lines that match the regular expressions from the ``regex`` argument. The configuration is read from the network device interrogated. regex The regular expression to match the confi...
r.. versionadded:: 2019. 2. 0
def config_lines_w_child(parent_regex, child_regex, source='running'): r''' .. versionadded:: 2019.2.0 Return the configuration lines that match the regular expressions from the ``parent_regex`` argument, having child lines matching ``child_regex``. The configuration is read from the network devic...
.. versionadded:: 2019. 2. 0
def config_lines_wo_child(parent_regex, child_regex, source='running'): ''' .. versionadded:: 2019.2.0 Return the configuration lines that match the regular expressions from the ``parent_regex`` argument, having the child lines *not* matching ``child_regex``. The configuration is read from th...
r.. versionadded:: 2019. 2. 0
def config_filter_lines(parent_regex, child_regex, source='running'): r''' .. versionadded:: 2019.2.0 Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child...
.. versionadded:: 2019. 2. 0
def config_tree(source='running', with_tags=False): ''' .. versionadded:: 2019.2.0 Transform Cisco IOS style configuration to structured Python dictionary. Depending on the value of the ``with_tags`` argument, this function may provide different views, valuable in different situations. source:...
.. versionadded:: 2019. 2. 0
def config_merge_tree(source='running', merge_config=None, merge_path=None, saltenv='base'): ''' .. versionadded:: 2019.2.0 Return the merge tree of the ``initial_config`` with the ``merge_config``, as a Python dictionary. source: `...
.. versionadded:: 2019. 2. 0
def config_merge_text(source='running', merge_config=None, merge_path=None, saltenv='base'): ''' .. versionadded:: 2019.2.0 Return the merge result of the configuration from ``source`` with the merge configuration, as plain text (without...
.. versionadded:: 2019. 2. 0
def config_merge_diff(source='running', merge_config=None, merge_path=None, saltenv='base'): ''' .. versionadded:: 2019.2.0 Return the merge diff, as text, after merging the merge config into the configuration source requested (without l...
.. versionadded:: 2019. 2. 0
def config_diff_tree(source1='candidate', candidate_path=None, source2='running', running_path=None): ''' .. versionadded:: 2019.2.0 Return the diff, as Python dictionary, between two different sources. The sources can be either specified u...
.. versionadded:: 2019. 2. 0
def scp_get(remote_path, local_path='', recursive=False, preserve_times=False, **kwargs): ''' .. versionadded:: 2019.2.0 Transfer files and directories from remote network device to the localhost of the Minion. .. note:: This function is only...
.. versionadded:: 2019. 2. 0
def scp_put(files, remote_path=None, recursive=False, preserve_times=False, saltenv='base', **kwargs): ''' .. versionadded:: 2019.2.0 Transfer files and directories to remote network device. .. note:: This function is only available o...
Return configuration
def _get_config(**kwargs): ''' Return configuration ''' config = { 'box_type': 'sealedbox', 'sk': None, 'sk_file': os.path.join(kwargs['opts'].get('pki_dir'), 'master/nacl'), 'pk': None, 'pk_file': os.path.join(kwargs['opts'].get('pki_dir'), 'master/nacl.pub'), ...
Return sk
def _get_sk(**kwargs): ''' Return sk ''' config = _get_config(**kwargs) key = salt.utils.stringutils.to_str(config['sk']) sk_file = config['sk_file'] if not key and sk_file: with salt.utils.files.fopen(sk_file, 'rb') as keyf: key = salt.utils.stringutils.to_unicode(keyf.r...
Return pk
def _get_pk(**kwargs): ''' Return pk ''' config = _get_config(**kwargs) pubkey = salt.utils.stringutils.to_str(config['pk']) pk_file = config['pk_file'] if not pubkey and pk_file: with salt.utils.files.fopen(pk_file, 'rb') as keyf: pubkey = salt.utils.stringutils.to_unico...
Use libnacl to generate a keypair.
def keygen(sk_file=None, pk_file=None, **kwargs): ''' Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file...
Alias to { box_type } _encrypt
def enc(data, **kwargs): ''' Alias to `{box_type}_encrypt` box_type: secretbox, sealedbox(default) ''' if 'keyfile' in kwargs: salt.utils.versions.warn_until( 'Neon', 'The \'keyfile\' argument has been deprecated and will be removed in Salt ' '{version}. ...
This is a helper function to encrypt a file and return its contents.
def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-bloc...
Alias to { box_type } _decrypt
def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' if 'keyfile' in kwargs: salt.utils.versions.warn_until( 'Neon', 'The \'keyfile\' argument has been deprecated and will be removed in Salt ' '{version}. ...
Encrypt data using a public key generated from nacl. keygen. The encryptd data can be decrypted using nacl. sealedbox_decrypt only with the secret key.
def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-ca...
Decrypt data using a secret key that was encrypted using a public key with nacl. sealedbox_encrypt.
def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF...
Encrypt data using a secret key generated from nacl. keygen. The same secret key can be used to decrypt the data using nacl. secretbox_decrypt.
def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --loc...
Decrypt data that was encrypted using nacl. secretbox_encrypt using the secret key that was generated from nacl. keygen.
def secretbox_decrypt(data, **kwargs): ''' Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key that was generated from `nacl.keygen`. CLI Examples: .. code-block:: bash salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.secretbox...
Ensure the grafana dashboard exists and is managed.
def present(name, base_dashboards_from_pillar=None, base_panels_from_pillar=None, base_rows_from_pillar=None, dashboard=None, profile='grafana'): ''' Ensure the grafana dashboard exists and is managed. name Name of the grafana dashboard. ...
Ensure the named grafana dashboard is absent.
def absent(name, profile='grafana'): ''' Ensure the named grafana dashboard is absent. name Name of the grafana dashboard. profile A pillar key or dict that contains grafana information ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if isinstance(pr...
Return a copy without fields that can differ.
def _cleaned(_dashboard): '''Return a copy without fields that can differ.''' dashboard = copy.deepcopy(_dashboard) for ignored_dashboard_field in _IGNORED_DASHBOARD_FIELDS: dashboard.pop(ignored_dashboard_field, None) for row in dashboard.get('rows', []): for ignored_row_field in _IGNO...
Return a dashboard with properties from parents.
def _inherited_dashboard(dashboard, base_dashboards_from_pillar, ret): '''Return a dashboard with properties from parents.''' base_dashboards = [] for base_dashboard_from_pillar in base_dashboards_from_pillar: base_dashboard = __salt__['pillar.get'](base_dashboard_from_pillar) if base_dashbo...
Return a row with properties from parents.
def _inherited_row(row, base_rows_from_pillar, ret): '''Return a row with properties from parents.''' base_rows = [] for base_row_from_pillar in base_rows_from_pillar: base_row = __salt__['pillar.get'](base_row_from_pillar) if base_row: base_rows.append(base_row) elif bas...
Return a panel with properties from parents.
def _inherited_panel(panel, base_panels_from_pillar, ret): '''Return a panel with properties from parents.''' base_panels = [] for base_panel_from_pillar in base_panels_from_pillar: base_panel = __salt__['pillar.get'](base_panel_from_pillar) if base_panel: base_panels.append(base...
Adjust panel spans to take up the available width.
def _auto_adjust_panel_spans(dashboard): '''Adjust panel spans to take up the available width. For each group of panels that would be laid out on the same level, scale up the unspecified panel spans to fill up the level. ''' for row in dashboard.get('rows', []): levels = [] current_...
Pin rows to the top of the dashboard.
def _ensure_pinned_rows(dashboard): '''Pin rows to the top of the dashboard.''' pinned_row_titles = __salt__['pillar.get'](_PINNED_ROWS_PILLAR) if not pinned_row_titles: return pinned_row_titles_lower = [] for title in pinned_row_titles: pinned_row_titles_lower.append(title.lower())...
Assign panels auto - incrementing IDs.
def _ensure_panel_ids(dashboard): '''Assign panels auto-incrementing IDs.''' panel_id = 1 for row in dashboard.get('rows', []): for panel in row.get('panels', []): panel['id'] = panel_id panel_id += 1
Explode annotation_tags into annotations.
def _ensure_annotations(dashboard): '''Explode annotation_tags into annotations.''' if 'annotation_tags' not in dashboard: return tags = dashboard['annotation_tags'] annotations = { 'enable': True, 'list': [], } for tag in tags: annotations['list'].append({ ...
Get a specific dashboard.
def _get(url, profile): '''Get a specific dashboard.''' request_url = "{0}/api/dashboards/{1}".format(profile.get('grafana_url'), url) response = requests.get( request_url, headers={ "Accept": "application/json", "Auth...
Delete a specific dashboard.
def _delete(url, profile): '''Delete a specific dashboard.''' request_url = "{0}/api/dashboards/{1}".format(profile.get('grafana_url'), url) response = requests.delete( request_url, headers={ "Accept": "application/json", ...
Update a specific dashboard.
def _update(dashboard, profile): '''Update a specific dashboard.''' payload = { 'dashboard': dashboard, 'overwrite': True } request_url = "{0}/api/dashboards/db".format(profile.get('grafana_url')) response = requests.post( request_url, headers={ "Authoriza...
Return a dictionary of changes between dashboards.
def _dashboard_diff(_new_dashboard, _old_dashboard): '''Return a dictionary of changes between dashboards.''' diff = {} # Dashboard diff new_dashboard = copy.deepcopy(_new_dashboard) old_dashboard = copy.deepcopy(_old_dashboard) dashboard_diff = DictDiffer(new_dashboard, old_dashboard) diff...
Strip falsey entries.
def _stripped(d): '''Strip falsey entries.''' ret = {} for k, v in six.iteritems(d): if v: ret[k] = v return ret
Given an email address checks the local cache if corresponding email address: channel_id mapping exists
def _retrieve_channel_id(email, profile='telemetry'): ''' Given an email address, checks the local cache if corresponding email address: channel_id mapping exists email Email escalation policy profile A dict of telemetry config information. ''' key = "telemetry.channels"...
Get all alert definitions associated with a given deployment or if metric_name is specified obtain the specific alert config
def get_alert_config(deployment_id, metric_name=None, api_key=None, profile="telemetry"): ''' Get all alert definitions associated with a given deployment or if metric_name is specified, obtain the specific alert config Returns dictionary or list of dictionaries. CLI Example: salt myminio...
Given an email address creates a notification - channels if one is not found and also returns the corresponding notification channel id.
def get_notification_channel_id(notify_channel, profile="telemetry"): ''' Given an email address, creates a notification-channels if one is not found and also returns the corresponding notification channel id. notify_channel Email escalation policy profile A dict of telemetry co...
get all the alarms set up against the current deployment
def get_alarms(deployment_id, profile="telemetry"): ''' get all the alarms set up against the current deployment Returns dictionary of alarm information CLI Example: salt myminion telemetry.get_alarms rs-ds033197 profile=telemetry ''' auth = _auth(profile=profile) try: r...
create an telemetry alarms.
def create_alarm(deployment_id, metric_name, data, api_key=None, profile="telemetry"): ''' create an telemetry alarms. data is a dict of alert configuration data. Returns (bool success, str message) tuple. CLI Example: salt myminion telemetry.create_alarm rs-ds033197 {} profile=telemetry...
update an telemetry alarms. data is a dict of alert configuration data.
def update_alarm(deployment_id, metric_name, data, api_key=None, profile="telemetry"): ''' update an telemetry alarms. data is a dict of alert configuration data. Returns (bool success, str message) tuple. CLI Example: salt myminion telemetry.update_alarm rs-ds033197 {} profile=telemetry ...
delete an alert specified by alert_id or if not specified blows away all the alerts in the current deployment.
def delete_alarms(deployment_id, alert_id=None, metric_name=None, api_key=None, profile='telemetry'): '''delete an alert specified by alert_id or if not specified blows away all the alerts in the current deployment. Returns (bool success, str message) tuple. CLI Example: salt myminion te...
Decompress returned HTTP content depending on the specified encoding. Currently supports identity/ none deflate and gzip which should cover 99% + of the content on the internet.
def __decompressContent(coding, pgctnt): ''' Decompress returned HTTP content depending on the specified encoding. Currently supports identity/none, deflate, and gzip, which should cover 99%+ of the content on the internet. ''' log.trace("Decompressing %s byte content with compression type: %s"...
Query a resource and decode the return data
def query(url, method='GET', params=None, data=None, data_file=None, header_dict=None, header_list=None, header_file=None, username=None, password=None, auth=None, decode=False, decode_type='auto', ...
Return the location of the ca bundle file. See the following article:
def get_ca_bundle(opts=None): ''' Return the location of the ca bundle file. See the following article: http://tinyurl.com/k7rx42a ''' if hasattr(get_ca_bundle, '__return_value__'): return get_ca_bundle.__return_value__ if opts is None: opts = {} opts_bundle = opts.get...
Attempt to update the CA bundle file from a URL
def update_ca_bundle( target=None, source=None, opts=None, merge_files=None, ): ''' Attempt to update the CA bundle file from a URL If not specified, the local location on disk (``target``) will be auto-detected, if possible. If it is not found, then a new locati...
Render a template
def _render(template, render, renderer, template_dict, opts): ''' Render a template ''' if render: if template_dict is None: template_dict = {} if not renderer: renderer = opts.get('renderer', 'jinja|yaml') rend = salt.loader.render(opts, {}) black...
Parse the Set - cookie header and return a list of cookies.
def parse_cookie_header(header): ''' Parse the "Set-cookie" header, and return a list of cookies. This function is here because Tornado's HTTPClient doesn't handle cookies. ''' attribs = ('expires', 'path', 'domain', 'version', 'httponly', 'secure', 'comment', 'max-age') # Split into cookie(s)...
Make sure no secret fields show up in logs
def sanitize_url(url, hide_fields): ''' Make sure no secret fields show up in logs ''' if isinstance(hide_fields, list): url_comps = splitquery(url) log_url = url_comps[0] if len(url_comps) > 1: log_url += '?' for pair in url_comps[1:]: url_tmp = N...
Recursive function to sanitize each component of the url.
def _sanitize_url_components(comp_list, field): ''' Recursive function to sanitize each component of the url. ''' if not comp_list: return '' elif comp_list[0].startswith('{0}='.format(field)): ret = '{0}=XXXXXXXXXX&'.format(field) comp_list.remove(comp_list[0]) retur...