text stringlengths 81 112k |
|---|
Return the state data from the master
def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeou... |
Output the data in lines, very nice for running commands
def output(data, **kwargs): # pylint: disable=unused-argument
'''
Output the data in lines, very nice for running commands
'''
ret = ''
if hasattr(data, 'keys'):
for key in data:
value = data[key]
# Don't blow... |
Recursively compare two configs, writing any needed changes to the
update_config and capturing changes in the changes dict.
def compare_and_update_config(config, update_config, changes, namespace=''):
'''
Recursively compare two configs, writing any needed changes to the
update_config and capturing cha... |
Manage a memcached key.
name
The key to manage
value
The value to set for that key
host
The memcached server IP address
port
The memcached server port
.. code-block:: yaml
foo:
memcached.managed:
- value: bar
def managed(name,
... |
Parse /etc/hosts file.
CLI Example:
.. code-block:: bash
salt '*' dnsutil.parse_hosts
def parse_hosts(hostsfile='/etc/hosts', hosts=None):
'''
Parse /etc/hosts file.
CLI Example:
.. code-block:: bash
salt '*' dnsutil.parse_hosts
'''
if not hosts:
try:
... |
Append a single line to the /etc/hosts file.
CLI Example:
.. code-block:: bash
salt '*' dnsutil.hosts_append /etc/hosts 127.0.0.1 ad1.yuk.co,ad2.yuk.co
def hosts_append(hostsfile='/etc/hosts', ip_addr=None, entries=None):
'''
Append a single line to the /etc/hosts file.
CLI Example:
... |
Remove a host from the /etc/hosts file. If doing so will leave a line
containing only an IP address, then the line will be deleted. This function
will leave comments and blank lines intact.
CLI Examples:
.. code-block:: bash
salt '*' dnsutil.hosts_remove /etc/hosts ad1.yuk.co
salt '*'... |
Parses a zone file. Can be passed raw zone data on the API level.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone
def parse_zone(zonefile=None, zone=None):
'''
Parses a zone file. Can be passed raw zone data on the API level.
CLI Example:
... |
Converts a time value to seconds.
As per RFC1035 (page 45), max time is 1 week, so anything longer (or
unreadable) will be set to one week (604800 seconds).
def _to_seconds(timestr):
'''
Converts a time value to seconds.
As per RFC1035 (page 45), max time is 1 week, so anything longer (or
unr... |
Return the A record(s) for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.A www.google.com
def A(host, nameserver=None):
'''
Return the A record(s) for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns... |
Return the AAAA record(s) for ``host``.
Always returns a list.
.. versionadded:: 2014.7.5
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.AAAA www.google.com
def AAAA(host, nameserver=None):
'''
Return the AAAA record(s) for ``host``.
Always returns a list.
.. versiona... |
Return a list of IPs of the nameservers for ``domain``
If 'resolve' is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.NS google.com
def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If 'resolve'... |
Return a list of lists for the MX of ``domain``.
If the 'resolve' argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved v... |
Return, store and update a dns serial for your zone files.
zone: a keyword for a specific zone
update: store an updated version of the serial in a grain
If ``update`` is False, the function will retrieve an existing serial or
return the current date if no serial is stored. Nothing will be stored
... |
Some things need to be init'd after the fork has completed
The easiest example is that one of these module types creates a thread
in the parent process, then once the fork happens you'll start getting
errors like "WARNING: Mixing fork() and threads detected; memory leaked."
def _post_fork_init(... |
This is the general passive maintenance process controller for the Salt
master.
This is where any data that needs to be cleanly maintained from the
master is maintained.
def run(self):
'''
This is the general passive maintenance process controller for the Salt
master.
... |
Evaluate accepted keys and create a msgpack file
which contains a list
def handle_key_cache(self):
'''
Evaluate accepted keys and create a msgpack file
which contains a list
'''
if self.opts['key_cache'] == 'sched':
keys = []
#TODO DRY from CKMini... |
Rotate the AES key rotation
def handle_key_rotate(self, now):
'''
Rotate the AES key rotation
'''
to_rotate = False
dfn = os.path.join(self.opts['cachedir'], '.dfn')
try:
stats = os.stat(dfn)
# Basic Windows permissions don't distinguish between
... |
Update git pillar
def handle_git_pillar(self):
'''
Update git pillar
'''
try:
for pillar in self.git_pillar:
pillar.fetch_remotes()
except Exception as exc:
log.error('Exception caught while updating git_pillar',
exc_... |
Evaluate the scheduler
def handle_schedule(self):
'''
Evaluate the scheduler
'''
try:
self.schedule.eval()
# Check if scheduler requires lower loop interval than
# the loop_interval setting
if self.schedule.loop_interval < self.loop_interv... |
Fire presence events if enabled
def handle_presence(self, old_present):
'''
Fire presence events if enabled
'''
# On the first run it may need more time for the EventPublisher
# to come up and be ready. Set the timeout to account for this.
if self.presence_events and sel... |
Get the configured backends and the intervals for any backend which
supports them, and set up the update "buckets". There will be one
bucket for each thing being updated at a given interval.
def fill_buckets(self):
'''
Get the configured backends and the intervals for any backend which
... |
Threading target which handles all updates for a given wait interval
def update_fileserver(self, interval, backends):
'''
Threading target which handles all updates for a given wait interval
'''
def _do_update():
log.debug(
'Performing fileserver updates for ... |
Start the update threads
def run(self):
'''
Start the update threads
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
# Clean out the fileserver backend cache
salt.daemons.masterapi.clean_fsbackend(self.opts)
for interval in self.buckets:
... |
Run pre flight checks. If anything in this method fails then the master
should not start up.
def _pre_flight(self):
'''
Run pre flight checks. If anything in this method fails then the master
should not start up.
'''
errors = []
critical_errors = []
try:... |
Turn on the master server components
def start(self):
'''
Turn on the master server components
'''
self._pre_flight()
log.info('salt-master is starting as user \'%s\'', salt.utils.user.get_user())
enable_sigusr1_handler()
enable_sigusr2_handler()
self._... |
Fire up halite!
def run(self):
'''
Fire up halite!
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
halite.start(self.hopts) |
Binds the reply server
def __bind(self):
'''
Binds the reply server
'''
if self.log_queue is not None:
salt.log.setup.set_multiprocessing_logging_queue(self.log_queue)
if self.log_queue_level is not None:
salt.log.setup.set_multiprocessing_logging_level(s... |
Bind to the local port
def __bind(self):
'''
Bind to the local port
'''
# using ZMQIOLoop since we *might* need zmq in there
install_zmq()
self.io_loop = ZMQDefaultLoop()
self.io_loop.make_current()
for req_channel in self.req_channels:
req_ch... |
The _handle_payload method is the key method used to figure out what
needs to be done with communication to the server
Example cleartext payload generated for 'salt myminion test.ping':
{'enc': 'clear',
'load': {'arg': [],
'cmd': 'publish',
'fun': '... |
Fire events with stat info if it's time
def _post_stats(self, stats):
'''
Fire events with stat info if it's time
'''
end_time = time.time()
if end_time - self.stat_clock > self.opts['master_stats_event_iter']:
# Fire the event with the stats and wipe the tracker
... |
Process a cleartext command
:param dict load: Cleartext payload
:return: The result of passing the load to a function in ClearFuncs corresponding to
the command specified in the load's 'cmd' key.
def _handle_clear(self, load):
'''
Process a cleartext command
:... |
Process a command sent via an AES key
:param str load: Encrypted payload
:return: The result of passing the load to a function in AESFuncs corresponding to
the command specified in the load's 'cmd' key.
def _handle_aes(self, data):
'''
Process a command sent via an AES... |
Start a Master Worker
def run(self):
'''
Start a Master Worker
'''
salt.utils.process.appendproctitle(self.name)
self.clear_funcs = ClearFuncs(
self.opts,
self.key,
)
self.aes_funcs = AESFuncs(self.opts)
salt.utils.crypt.reinit_cr... |
Set the local file objects from the file server interface
def __setup_fileserver(self):
'''
Set the local file objects from the file server interface
'''
# Avoid circular import
import salt.fileserver
self.fs_ = salt.fileserver.Fileserver(self.opts)
self._serve_f... |
Take a minion id and a string signed with the minion private key
The string needs to verify as 'salt' with the minion public key
:param str id_: A minion ID
:param str token: A string signed with the minion private key
:rtype: bool
:return: Boolean indicating whether or not the... |
Verify that the passed information authorized a minion to execute
:param dict clear_load: A publication load from a minion
:rtype: bool
:return: A boolean indicating if the minion is allowed to publish the command in the load
def __verify_minion_publish(self, clear_load):
'''
... |
A utility function to perform common verification steps.
:param dict load: A payload received from a minion
:param list verify_keys: A list of strings that should be present in a
given load
:rtype: bool
:rtype: dict
:return: The original load (except for the token) if t... |
Return the results from an external node classifier if one is
specified
:param dict load: A payload received from a minion
:return: The results from an external node classifier
def _master_tops(self, load):
'''
Return the results from an external node classifier if one is
... |
Gathers the data from the specified minions' mine
:param dict load: A payload received from a minion
:rtype: dict
:return: Mine data from the specified minions
def _mine_get(self, load):
'''
Gathers the data from the specified minions' mine
:param dict load: A payload... |
Store the mine data
:param dict load: A payload received from a minion
:rtype: bool
:return: True if the data has been stored in the mine
def _mine(self, load):
'''
Store the mine data
:param dict load: A payload received from a minion
:rtype: bool
:r... |
Allow the minion to delete a specific function from its own mine
:param dict load: A payload received from a minion
:rtype: bool
:return: Boolean indicating whether or not the given function was deleted from the mine
def _mine_delete(self, load):
'''
Allow the minion to delete... |
Allow the minion to delete all of its own mine contents
:param dict load: A payload received from a minion
def _mine_flush(self, load):
'''
Allow the minion to delete all of its own mine contents
:param dict load: A payload received from a minion
'''
load = self.__veri... |
Allows minions to send files to the master, files are sent to the
master file cache
def _file_recv(self, load):
'''
Allows minions to send files to the master, files are sent to the
master file cache
'''
if any(key not in load for key in ('id', 'path', 'loc')):
... |
Return the pillar data for the minion
:param dict load: Minion payload
:rtype: dict
:return: The pillar data for the minion
def _pillar(self, load):
'''
Return the pillar data for the minion
:param dict load: Minion payload
:rtype: dict
:return: The p... |
Receive an event from the minion and fire it on the master event
interface
:param dict load: The minion payload
def _minion_event(self, load):
'''
Receive an event from the minion and fire it on the master event
interface
:param dict load: The minion payload
''... |
Act on specific events from minions
def _handle_minion_event(self, load):
'''
Act on specific events from minions
'''
id_ = load['id']
if load.get('tag', '') == '_salt_error':
log.error(
'Received minion error from [%s]: %s',
id_, load... |
Handle the return data sent from the minions.
Takes the return, verifies it and fires it on the master event bus.
Typically, this event is consumed by the Salt CLI waiting on the other
end of the event bus but could be heard by any listener on the bus.
:param dict load: The minion payl... |
Receive a syndic minion return and format it to look like returns from
individual minions.
:param dict load: The minion payload
def _syndic_return(self, load):
'''
Receive a syndic minion return and format it to look like returns from
individual minions.
:param dict lo... |
Execute a runner from a minion, return the runner's function data
:param dict clear_load: The minion payload
:rtype: dict
:return: The runner function data
def minion_runner(self, clear_load):
'''
Execute a runner from a minion, return the runner's function data
:para... |
Request the return data from a specific jid, only allowed
if the requesting minion also initialted the execution.
:param dict load: The minion payload
:rtype: dict
:return: Return data corresponding to a given JID
def pub_ret(self, load):
'''
Request the return data fr... |
Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt functions, so the minions can only publish allowed salt ... |
Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt functions, so the minions can only publish allowed salt ... |
Allow a minion to request revocation of its own key
:param dict load: The minion payload
:rtype: dict
:return: If the load is invalid, it may be returned. No key operation is performed.
:rtype: bool
:return: True if key was revoked, False if not
def revoke_auth(self, load):
... |
Wrapper for running functions executed with AES encryption
:param function func: The function to run
:return: The result of the master function that was called
def run_func(self, func, load):
'''
Wrapper for running functions executed with AES encryption
:param function func: ... |
Send a master control function back to the runner system
def runner(self, clear_load):
'''
Send a master control function back to the runner system
'''
# All runner ops pass through eauth
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load)
#... |
Send a master control function back to the wheel system
def wheel(self, clear_load):
'''
Send a master control function back to the wheel system
'''
# All wheel ops pass through eauth
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load)
# Aut... |
Create and return an authentication token, the clear load needs to
contain the eauth key and the needed authentication creds.
def mk_token(self, clear_load):
'''
Create and return an authentication token, the clear load needs to
contain the eauth key and the needed authentication creds.... |
This method sends out publications to the minions, it can only be used
by the LocalClient.
def publish(self, clear_load):
'''
This method sends out publications to the minions, it can only be used
by the LocalClient.
'''
extra = clear_load.get('kwargs', {})
publ... |
Return a jid for this publication
def _prep_jid(self, clear_load, extra):
'''
Return a jid for this publication
'''
# the jid in clear_load can be None, '', or something else. this is an
# attempt to clean up the value before passing to plugins
passed_jid = clear_load['j... |
Take a load and send it across the network to connected minions
def _send_pub(self, load):
'''
Take a load and send it across the network to connected minions
'''
for transport, opts in iter_transport_opts(self.opts):
chan = salt.transport.server.PubServerChannel.factory(opt... |
Take a load and send it across the network to ssh minions
def _send_ssh_pub(self, load, ssh_minions=False):
'''
Take a load and send it across the network to ssh minions
'''
if self.opts['enable_ssh_minions'] is True and ssh_minions is True:
log.debug('Send payload to ssh mi... |
Take a given load and perform the necessary steps
to prepare a publication.
TODO: This is really only bound by temporal cohesion
and thus should be refactored even further.
def _prep_pub(self, minions, jid, clear_load, extra, missing):
'''
Take a given load and perform the nece... |
Makes sure the specified row is absent in db. If multiple rows
match where_sql, then the state will fail.
name
Only used as the unique ID
db
The database file name
table
The table name to check
where_sql
The sql to select the row to check
where_args
... |
Checks to make sure the given row exists. If row exists and update is True
then row will be updated with data. Otherwise it will leave existing
row unmodified and check it against data. If the existing data
doesn't match data_check the state will fail. If the row doesn't
exist then it will insert data ... |
Make sure the specified table does not exist
name
The name of the table
db
The name of the database file
def table_absent(name, db):
'''
Make sure the specified table does not exist
name
The name of the table
db
The name of the database file
'''
chang... |
Make sure the specified table exists with the specified schema
name
The name of the table
db
The name of the database file
schema
The dictionary containing the schema information
force
If the name of the table exists and force is set to False,
the state will f... |
Matches based on range cluster
def match(tgt, opts=None):
'''
Matches based on range cluster
'''
if not opts:
opts = __opts__
if HAS_RANGE:
range_ = seco.range.Range(opts['range_server'])
try:
return opts['grains']['fqdn'] in range_.expand(tgt)
except sec... |
Return data to a Cassandra ColumnFamily
def returner(ret):
'''
Return data to a Cassandra ColumnFamily
'''
consistency_level = getattr(pycassa.ConsistencyLevel,
__opts__['cassandra.consistency_level'])
pool = pycassa.ConnectionPool(__opts__['cassandra.keyspace'],
... |
Update and get the random script to a random place
CLI Example:
.. code-block:: bash
salt '*' seed.prep_bootstrap /tmp
def prep_bootstrap(mpt):
'''
Update and get the random script to a random place
CLI Example:
.. code-block:: bash
salt '*' seed.prep_bootstrap /tmp
'... |
Seed a location (disk image, directory, or block device) with the
minion config, approve the minion's key, and/or install salt-minion.
CLI Example:
.. code-block:: bash
salt 'minion' seed.apply path id [config=config_data] \\
[gen_key=(true|false)] [approve_key=(true|false)] \\
... |
Generate keys and config and put them in a tmp directory.
pub_key
absolute path or file content of an optional preseeded salt key
priv_key
absolute path or file content of an optional preseeded salt key
CLI Example:
.. code-block:: bash
salt 'minion' seed.mkconfig [config=co... |
Determine whether salt-minion is installed and, if not,
install it.
Return True if install is successful or already installed.
def _install(mpt):
'''
Determine whether salt-minion is installed and, if not,
install it.
Return True if install is successful or already installed.
'''
_check... |
Check that the resolv.conf is present and populated
def _check_resolv(mpt):
'''
Check that the resolv.conf is present and populated
'''
resolv = os.path.join(mpt, 'etc/resolv.conf')
replace = False
if os.path.islink(resolv):
resolv = os.path.realpath(resolv)
if not os.path.isdir... |
helper function to get the results of ``netsh -f content.txt``
Running ``netsh`` will drop you into a ``netsh`` prompt where you can issue
``netsh`` commands. You can put a series of commands in an external file and
run them as if from a ``netsh`` prompt using the ``-f`` switch. That's what
this functi... |
Get the firewall property from the specified profile in the specified store
as returned by ``netsh advfirewall``.
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
section (str):
The ... |
Gets all the properties for the specified profile in the specified store
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
store (str):
The store to use. This is either the local firewall... |
Gets all properties for all profiles in the specified store
Args:
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
R... |
Set the firewall inbound/outbound settings for the specified profile and
store
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
inbound (str):
The inbound setting. If ``None`` is... |
Configure logging settings for the Windows firewall.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The logging setting to configure. Valid options are:
... |
Configure firewall settings.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The firewall setting to configure. Valid options are:
- localfirewallrules
... |
Configure the firewall state.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
state (str):
The firewall state. Valid options are:
- on
- off
- n... |
Parse the aliases file, and return a list of line components:
[
(alias1, target1, comment1),
(alias2, target2, comment2),
]
def __parse_aliases():
'''
Parse the aliases file, and return a list of line components:
[
(alias1, target1, comment1),
(alias2, target2, comment2),
... |
Write a new copy of the aliases file. Lines is a list of lines
as returned by __parse_aliases.
def __write_aliases_file(lines):
'''
Write a new copy of the aliases file. Lines is a list of lines
as returned by __parse_aliases.
'''
afn = __get_aliases_filename()
adir = os.path.dirname(afn)... |
Return the aliases found in the aliases file in this format::
{'alias': 'target'}
CLI Example:
.. code-block:: bash
salt '*' aliases.list_aliases
def list_aliases():
'''
Return the aliases found in the aliases file in this format::
{'alias': 'target'}
CLI Example:
... |
Return true if the alias/target is set
CLI Example:
.. code-block:: bash
salt '*' aliases.has_target alias target
def has_target(alias, target):
'''
Return true if the alias/target is set
CLI Example:
.. code-block:: bash
salt '*' aliases.has_target alias target
'''
... |
Set the entry in the aliases file for the given alias, this will overwrite
any previous entry for the given alias or create a new one if it does not
exist.
CLI Example:
.. code-block:: bash
salt '*' aliases.set_target alias target
def set_target(alias, target):
'''
Set the entry in t... |
Remove an entry from the aliases file
CLI Example:
.. code-block:: bash
salt '*' aliases.rm_alias alias
def rm_alias(alias):
'''
Remove an entry from the aliases file
CLI Example:
.. code-block:: bash
salt '*' aliases.rm_alias alias
'''
if not get_target(alias):
... |
Gather the specified data from the minion data cache
def gather_cache(self):
'''
Gather the specified data from the minion data cache
'''
cache = {'grains': {}, 'pillar': {}}
if self.grains or self.pillar:
if self.opts.get('minion_data_cache'):
minion... |
Start the system!
def start_runtime(self):
'''
Start the system!
'''
while True:
try:
self.call_runtime()
except Exception:
log.error('Exception in Thorium: ', exc_info=True)
time.sleep(self.opts['thorium_interval']... |
Compile the top file and return the lowstate for the thorium runtime
to iterate over
def get_chunks(self, exclude=None, whitelist=None):
'''
Compile the top file and return the lowstate for the thorium runtime
to iterate over
'''
ret = {}
err = []
try:
... |
iterate over the available events and return a list of events
def get_events(self):
'''
iterate over the available events and return a list of events
'''
ret = []
while True:
event = self.event.get_event(wait=1, full=True)
if event is None:
... |
Execute the runtime
def call_runtime(self):
'''
Execute the runtime
'''
cache = self.gather_cache()
chunks = self.get_chunks()
interval = self.opts['thorium_interval']
recompile = self.opts.get('thorium_recompile', 300)
r_start = time.time()
while... |
Decorator for common function argument validation
def _validate(wrapped):
'''
Decorator for common function argument validation
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
container_type = kwargs.get('container_type')
exec_driver = kwargs.get('exec_driver')
v... |
Wrapper for cp.cache_file which raises an error if the file was unable to
be cached.
CLI Example:
.. code-block:: bash
salt myminion container_resource.cache_file salt://foo/bar/baz.txt
def cache_file(source):
'''
Wrapper for cp.cache_file which raises an error if the file was unable to
... |
Common logic for running shell commands in containers
path
path to the container parent (for LXC only)
default: /var/lib/lxc (system default)
CLI Example:
.. code-block:: bash
salt myminion container_resource.run mycontainer 'ps aux' container_type=docker exec_driver=nsenter outp... |
Common logic for copying files to containers
path
path to the container parent (for LXC only)
default: /var/lib/lxc (system default)
CLI Example:
.. code-block:: bash
salt myminion container_resource.copy_to mycontainer /local/file/path /container/file/path container_type=docker ... |
Directly calls the given function with arguments
def execute(opts, data, func, args, kwargs):
'''
Directly calls the given function with arguments
'''
if data['fun'] == 'saltutil.find_job':
return __executors__['direct_call.execute'](opts, data, func, args, kwargs)
if data['fun'] in DOCKER_... |
Execute the salt command line
def run(self):
'''
Execute the salt command line
'''
import salt.client
self.parse_args()
if self.config['log_level'] not in ('quiet', ):
# Setup file logging!
self.setup_logfile_logger()
verify_log(self.... |
Display returns summary
def _print_returns_summary(self, ret):
'''
Display returns summary
'''
return_counter = 0
not_return_counter = 0
not_return_minions = []
not_response_minions = []
not_connected_minions = []
failed_minions = []
for e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.