desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Query basic instance information'
| def query(self, query_type='list_nodes'):
| mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts['selected_query_option'] = 'list_nodes'
return mapper.map_providers_parallel(query_type)
|
'Query all instance information'
| def full_query(self, query_type='list_nodes_full'):
| mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts['selected_query_option'] = 'list_nodes_full'
return mapper.map_providers_parallel(query_type)
|
'Query select instance information'
| def select_query(self, query_type='list_nodes_select'):
| mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts['selected_query_option'] = 'list_nodes_select'
return mapper.map_providers_parallel(query_type)
|
'Query select instance information'
| def min_query(self, query_type='list_nodes_min'):
| mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts['selected_query_option'] = 'list_nodes_min'
return mapper.map_providers_parallel(query_type)
|
'Pass in a profile to create, names is a list of vm names to allocate
vm_overrides is a special dict that will be per node options
overrides
Example:
.. code-block:: python
>>> client= salt.cloud.CloudClient(path=\'/etc/salt/cloud\')
>>> client.profile(\'do_512_git\', names=[\'minion01\',])
{\'minion01\': {u\'backups_a... | def profile(self, profile, names, vm_overrides=None, **kwargs):
| if (not vm_overrides):
vm_overrides = {}
kwargs['profile'] = profile
mapper = salt.cloud.Map(self._opts_defaults(**kwargs))
if isinstance(names, six.string_types):
names = names.split(',')
return salt.utils.simple_types_filter(mapper.run_profile(profile, names, vm_overrides=vm_overri... |
'Pass in a location for a map to execute'
| def map_run(self, path=None, **kwargs):
| kwarg = {}
if path:
kwarg['map'] = path
kwarg.update(kwargs)
mapper = salt.cloud.Map(self._opts_defaults(**kwarg))
dmap = mapper.map_data()
return salt.utils.simple_types_filter(mapper.run_map(dmap))
|
'Destroy the named VMs'
| def destroy(self, names):
| mapper = salt.cloud.Map(self._opts_defaults(destroy=True))
if isinstance(names, six.string_types):
names = names.split(',')
return salt.utils.simple_types_filter(mapper.destroy(names))
|
'Create the named VMs, without using a profile
Example:
.. code-block:: python
client.create(provider=\'my-ec2-config\', names=[\'myinstance\'],
image=\'ami-1624987f\', size=\'t1.micro\', ssh_username=\'ec2-user\',
securitygroup=\'default\', delvol_on_destroy=True)'
| def create(self, provider, names, **kwargs):
| mapper = salt.cloud.Map(self._opts_defaults())
providers = self.opts['providers']
if (provider in providers):
provider += ':{0}'.format(next(six.iterkeys(providers[provider])))
else:
return False
if isinstance(names, six.string_types):
names = names.split(',')
ret = {}
... |
'Perform actions with block storage devices
Example:
.. code-block:: python
client.extra_action(names=[\'myblock\'], action=\'volume_create\',
provider=\'my-nova\', kwargs={\'voltype\': \'SSD\', \'size\': 1000}
client.extra_action(names=[\'salt-net\'], action=\'network_create\',
provider=\'my-nova\', kwargs={\'cidr\': ... | def extra_action(self, names, provider, action, **kwargs):
| mapper = salt.cloud.Map(self._opts_defaults())
providers = mapper.map_providers_parallel()
if (provider in providers):
provider += ':{0}'.format(next(six.iterkeys(providers[provider])))
else:
return False
if isinstance(names, six.string_types):
names = names.split(',')
re... |
'Execute a single action via the cloud plugin backend
Examples:
.. code-block:: python
client.action(fun=\'show_instance\', names=[\'myinstance\'])
client.action(fun=\'show_image\', provider=\'my-ec2-config\',
kwargs={\'image\': \'ami-10314d79\'}'
| def action(self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None):
| if (kwargs is None):
kwargs = {}
mapper = salt.cloud.Map(self._opts_defaults(action=fun, names=names, **kwargs))
if instance:
if names:
raise SaltCloudConfigError("Please specify either a list of 'names' or a single 'instance', but not both.... |
'Return the configured providers'
| def get_configured_providers(self):
| providers = set()
for (alias, drivers) in six.iteritems(self.opts['providers']):
if (len(drivers) > 1):
for driver in drivers:
providers.add('{0}:{1}'.format(alias, driver))
continue
providers.add(alias)
return providers
|
'Get a dict describing the configured providers'
| def lookup_providers(self, lookup):
| if (lookup is None):
lookup = 'all'
if (lookup == 'all'):
providers = set()
for (alias, drivers) in six.iteritems(self.opts['providers']):
for driver in drivers:
providers.add((alias, driver))
if (not providers):
raise SaltCloudSystemExit('... |
'Return a dictionary describing the configured profiles'
| def lookup_profiles(self, provider, lookup):
| if (provider is None):
provider = 'all'
if (lookup is None):
lookup = 'all'
if (lookup == 'all'):
profiles = set()
provider_profiles = set()
for (alias, info) in six.iteritems(self.opts['profiles']):
providers = info.get('provider')
if provider... |
'Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs'
| def map_providers(self, query='list_nodes', cached=False):
| if ((cached is True) and (query in self.__cached_provider_queries)):
return self.__cached_provider_queries[query]
pmap = {}
for (alias, drivers) in six.iteritems(self.opts['providers']):
for (driver, details) in six.iteritems(drivers):
fun = '{0}.{1}'.format(driver, query)
... |
'Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs
Same as map_providers but query in parallel.'
| def map_providers_parallel(self, query='list_nodes', cached=False):
| if ((cached is True) and (query in self.__cached_provider_queries)):
return self.__cached_provider_queries[query]
opts = self.opts.copy()
multiprocessing_data = []
opts['providers'] = self._optimize_providers(opts['providers'])
for (alias, drivers) in six.iteritems(opts['providers']):
... |
'Return an optimized mapping of available providers'
| def _optimize_providers(self, providers):
| new_providers = {}
provider_by_driver = {}
for (alias, driver) in six.iteritems(providers):
for (name, data) in six.iteritems(driver):
if (name not in provider_by_driver):
provider_by_driver[name] = {}
provider_by_driver[name][alias] = data
for (driver, pr... |
'Return a mapping of all location data for available providers'
| def location_list(self, lookup='all'):
| data = {}
lookups = self.lookup_providers(lookup)
if (not lookups):
return data
for (alias, driver) in lookups:
fun = '{0}.avail_locations'.format(driver)
if (fun not in self.clouds):
log.debug("The '{0}' cloud driver defined under '{1}' provider ... |
'Return a mapping of all image data for available providers'
| def image_list(self, lookup='all'):
| data = {}
lookups = self.lookup_providers(lookup)
if (not lookups):
return data
for (alias, driver) in lookups:
fun = '{0}.avail_images'.format(driver)
if (fun not in self.clouds):
log.debug("The '{0}' cloud driver defined under '{1}' provider ... |
'Return a mapping of all image data for available providers'
| def size_list(self, lookup='all'):
| data = {}
lookups = self.lookup_providers(lookup)
if (not lookups):
return data
for (alias, driver) in lookups:
fun = '{0}.avail_sizes'.format(driver)
if (fun not in self.clouds):
log.debug("The '{0}' cloud driver defined under '{1}' provider a... |
'Return a mapping of all image data for available providers'
| def provider_list(self, lookup='all'):
| data = {}
lookups = self.lookup_providers(lookup)
if (not lookups):
return data
for (alias, driver) in lookups:
if (alias not in data):
data[alias] = {}
if (driver not in data[alias]):
data[alias][driver] = {}
return data
|
'Return a mapping of all configured profiles'
| def profile_list(self, provider, lookup='all'):
| data = {}
lookups = self.lookup_profiles(provider, lookup)
if (not lookups):
return data
for (alias, driver) in lookups:
if (alias not in data):
data[alias] = {}
if (driver not in data[alias]):
data[alias][driver] = {}
return data
|
'Create/Verify the VMs in the VM data'
| def create_all(self):
| ret = []
for (vm_name, vm_details) in six.iteritems(self.opts['profiles']):
ret.append({vm_name: self.create(vm_details)})
return ret
|
'Destroy the named VMs'
| def destroy(self, names, cached=False):
| processed = {}
names = set(names)
matching = self.get_running_by_names(names, cached=cached)
vms_to_destroy = set()
parallel_data = []
for (alias, drivers) in six.iteritems(matching):
for (driver, vms) in six.iteritems(drivers):
for name in vms:
if (name in na... |
'Reboot the named VMs'
| def reboot(self, names):
| ret = []
pmap = self.map_providers_parallel()
acts = {}
for (prov, nodes) in six.iteritems(pmap):
acts[prov] = []
for node in nodes:
if (node in names):
acts[prov].append(node)
for (prov, names_) in six.iteritems(acts):
fun = '{0}.reboot'.format(pr... |
'Create a single VM'
| def create(self, vm_, local_master=True):
| output = {}
minion_dict = salt.config.get_cloud_config_value('minion', vm_, self.opts, default={})
(alias, driver) = vm_['provider'].split(':')
fun = '{0}.create'.format(driver)
if (fun not in self.clouds):
log.error("Creating '{0[name]}' using '{0[provider]}' as the provid... |
'Extra actions'
| def extras(self, extra_):
| output = {}
(alias, driver) = extra_['provider'].split(':')
fun = '{0}.{1}'.format(driver, extra_['action'])
if (fun not in self.clouds):
log.error("Creating '{0[name]}' using '{0[provider]}' as the provider cannot complete since '{1}' is not available".for... |
'Parse over the options passed on the command line and determine how to
handle them'
| def run_profile(self, profile, names, vm_overrides=None):
| if (profile not in self.opts['profiles']):
msg = 'Profile {0} is not defined'.format(profile)
log.error(msg)
return {'Error': msg}
ret = {}
if (not vm_overrides):
vm_overrides = {}
try:
with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc:
... |
'Perform an action on a VM which may be specific to this cloud provider'
| def do_action(self, names, kwargs):
| ret = {}
invalid_functions = {}
names = set(names)
for (alias, drivers) in six.iteritems(self.map_providers_parallel()):
if (not names):
break
for (driver, vms) in six.iteritems(drivers):
if (not names):
break
valid_function = True
... |
'Perform a function against a cloud provider'
| def do_function(self, prov, func, kwargs):
| matches = self.lookup_providers(prov)
if (len(matches) > 1):
raise SaltCloudSystemExit("More than one results matched '{0}'. Please specify one of: {1}".format(prov, ', '.join(['{0}:{1}'.format(alias, driver) for (alias, driver) in matches])))
(alias, driver) = match... |
'Remove any mis-configured cloud providers from the available listing'
| def __filter_non_working_providers(self):
| for (alias, drivers) in six.iteritems(self.opts['providers'].copy()):
for driver in drivers.copy():
fun = '{0}.get_configured_provider'.format(driver)
if (fun not in self.clouds):
log.warning("The cloud driver, '{0}', configured under the '{1}' ... |
'Read in the specified map file and return the map structure'
| def read(self):
| map_ = None
if (self.opts.get('map', None) is None):
if (self.opts.get('map_data', None) is None):
return {}
else:
map_ = self.opts['map_data']
if (not map_):
local_minion_opts = copy.deepcopy(self.opts)
local_minion_opts['file_client'] = 'local'
... |
'Create a data map of what to execute on'
| def map_data(self, cached=False):
| ret = {'create': {}}
pmap = self.map_providers_parallel(cached=cached)
exist = set()
defined = set()
for (profile_name, nodes) in six.iteritems(self.rendered_map):
if (profile_name not in self.opts['profiles']):
msg = "The required profile, '{0}', defined in the... |
'Execute the contents of the VM map'
| def run_map(self, dmap):
| if self._has_loop(dmap):
msg = 'Uh-oh, that cloud map has a dependency loop!'
log.error(msg)
raise SaltCloudException(msg)
for (key, val) in six.iteritems(dmap['create']):
log.info('Calculating dependencies for {0}'.format(key))
level = 0
... |
'Execute the salt-cloud command line'
| def run(self):
| self.parse_args()
salt_master_user = self.config.get('user')
if (salt_master_user is None):
salt_master_user = salt.utils.get_user()
if (not check_user(salt_master_user)):
self.error("If salt-cloud is running on a master machine, salt-cloud needs to run ... |
'In pack, if any of the values are None they will be replaced with an
empty context-specific dict'
| def __init__(self, module_dirs, opts=None, tag=u'module', loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, proxy=None, virtual_funcs=None):
| self.inject_globals = {}
self.pack = ({} if (pack is None) else pack)
if (opts is None):
opts = {}
threadsafety = (not opts.get(u'multiprocessing'))
self.context_dict = salt.utils.context.ContextDict(threadsafe=threadsafety)
self.opts = self.__prep_mod_opts(opts)
self.module_dirs = m... |
'Override the __getitem__ in order to decorate the returned function if we need
to last-minute inject globals'
| def __getitem__(self, item):
| func = super(LazyLoader, self).__getitem__(item)
if self.inject_globals:
return global_injector_decorator(self.inject_globals)(func)
else:
return func
|
'Allow for "direct" attribute access-- this allows jinja templates to
access things like `salt.test.ping()`'
| def __getattr__(self, mod_name):
| if (mod_name in (u'__getstate__', u'__setstate__')):
return object.__getattribute__(self, mod_name)
try:
return object.__getattr__(self, mod_name)
except AttributeError:
pass
if ((mod_name not in self.loaded_modules) and (not self.loaded)):
for name in self._iter_files(mo... |
'Return the error string for a missing function.
This can range from "not available\' to "__virtual__" returned False'
| def missing_fun_string(self, function_name):
| mod_name = function_name.split(u'.')[0]
if (mod_name in self.loaded_modules):
return u"'{0}' is not available.".format(function_name)
else:
try:
reason = self.missing_modules[mod_name]
except KeyError:
return u"'{0}' is not available.".format... |
'refresh the mapping of the FS on disk'
| def refresh_file_mapping(self):
| self.suffix_map = {}
suffix_order = [u'']
for (suffix, mode, kind) in SUFFIXES:
self.suffix_map[suffix] = (suffix, mode, kind)
suffix_order.append(suffix)
if (self.opts.get(u'cython_enable', True) is True):
try:
global pyximport
pyximport = __import__(u'py... |
'Clear the dict'
| def clear(self):
| super(LazyLoader, self).clear()
self.loaded_files = set()
self.missing_modules = {}
self.loaded_modules = {}
if hasattr(self, u'opts'):
self.refresh_file_mapping()
self.initial_load = False
|
'Strip out of the opts any logger instance'
| def __prep_mod_opts(self, opts):
| if (u'__grains__' not in self.pack):
self.context_dict[u'grains'] = opts.get(u'grains', {})
self.pack[u'__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, u'grains', override_name=u'grains')
if (u'__pillar__' not in self.pack):
self.context_dict[u'pillar'] = opts.... |
'Iterate over all file_mapping files in order of closeness to mod_name'
| def _iter_files(self, mod_name):
| if (mod_name in self.file_mapping):
(yield mod_name)
for k in self.file_mapping:
if (mod_name in k):
(yield k)
for k in self.file_mapping:
if (mod_name not in k):
(yield k)
|
'Load a single item if you have it'
| def _load(self, key):
| if ((not isinstance(key, six.string_types)) or (u'.' not in key)):
raise KeyError
(mod_name, _) = key.split(u'.', 1)
if (mod_name in self.missing_modules):
return True
if (self.whitelist and (mod_name not in self.whitelist)):
raise KeyError
def _inner_load(mod_name):
... |
'Load all of them'
| def _load_all(self):
| for name in self.file_mapping:
if ((name in self.loaded_files) or (name in self.missing_modules)):
continue
self._load_module(name)
self.loaded = True
|
'Apply the __outputter__ variable to the functions'
| def _apply_outputter(self, func, mod):
| if hasattr(mod, u'__outputter__'):
outp = mod.__outputter__
if (func.__name__ in outp):
func.__outputter__ = outp[func.__name__]
|
'Given a loaded module and its default name determine its virtual name
This function returns a tuple. The first value will be either True or
False and will indicate if the module should be loaded or not (i.e. if
it threw and exception while processing its __virtual__ function). The
second value is the determined virtua... | def process_virtual(self, mod, module_name, virtual_func=u'__virtual__'):
| virtual_aliases = getattr(mod, u'__virtual_aliases__', tuple())
try:
error_reason = None
if (hasattr(mod, u'__virtual__') and inspect.isfunction(mod.__virtual__)):
try:
start = time.time()
virtual = getattr(mod, virtual_func)()
if isins... |
'Create a salt master server instance
:param dict opts: The salt options dictionary'
| def __init__(self, opts):
| self.opts = opts
self.master_key = salt.crypt.MasterKeys(self.opts)
self.key = self.__prep_key()
|
'A key needs to be placed in the filesystem with permissions 0400 so
clients are required to run as root.'
| def __prep_key(self):
| return salt.daemons.masterapi.access_keys(self.opts)
|
'Create a maintenance instance
:param dict opts: The salt options'
| def __init__(self, opts, log_queue=None):
| super(Maintenance, self).__init__(log_queue=log_queue)
self.opts = opts
self.loop_interval = int(self.opts[u'loop_interval'])
self.rotate = int(time.time())
self.serial = salt.payload.Serial(self.opts)
|
'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(self):
| self.fileserver = salt.fileserver.Fileserver(self.opts)
ropts = dict(self.opts)
ropts[u'quiet'] = True
runner_client = salt.runner.RunnerClient(ropts)
self.returners = salt.loader.returners(self.opts, {})
self.schedule = salt.utils.schedule.Schedule(self.opts, runner_client.functions_dict(), ret... |
'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):
| salt.utils.appendproctitle(u'Maintenance')
self._post_fork_init()
last = int(time.time())
salt.daemons.masterapi.clean_fsbackend(self.opts)
old_present = set()
while True:
now = int(time.time())
if ((now - last) >= self.loop_interval):
salt.daemons.masterapi.clean_old... |
'Evaluate accepted keys and create a msgpack file
which contains a list'
| def handle_key_cache(self):
| if (self.opts[u'key_cache'] == u'sched'):
keys = []
if (self.opts[u'transport'] in (u'zeromq', u'tcp')):
acc = u'minions'
else:
acc = u'accepted'
for fn_ in os.listdir(os.path.join(self.opts[u'pki_dir'], acc)):
if ((not fn_.startswith(u'.')) and os... |
'Rotate the AES key rotation'
| def handle_key_rotate(self, now):
| to_rotate = False
dfn = os.path.join(self.opts[u'cachedir'], u'.dfn')
try:
stats = os.stat(dfn)
if (salt.utils.platform.is_windows() and (not os.access(dfn, os.W_OK))):
to_rotate = True
os.chmod(dfn, (stat.S_IRUSR | stat.S_IWUSR))
elif (stats.st_mode == 33024)... |
'Update git pillar'
| def handle_git_pillar(self):
| try:
for pillar in self.git_pillar:
pillar.update()
except Exception as exc:
log.error(u'Exception caught while updating git_pillar', exc_info=True)
|
'Evaluate the scheduler'
| def handle_schedule(self):
| try:
self.schedule.eval()
if (self.schedule.loop_interval < self.loop_interval):
self.loop_interval = self.schedule.loop_interval
except Exception as exc:
log.error(u'Exception %s occurred in scheduled job', exc)
|
'Fire presence events if enabled'
| def handle_presence(self, old_present):
| if self.presence_events:
present = self.ckminions.connected_ids()
new = present.difference(old_present)
lost = old_present.difference(present)
if (new or lost):
data = {u'new': list(new), u'lost': list(lost)}
self.event.fire_event(data, tagify(u'change', u'pre... |
'Create a salt master server instance
:param dict: The salt options'
| def __init__(self, opts):
| if HAS_ZMQ:
try:
zmq_version_info = zmq.zmq_version_info()
except AttributeError:
zmq_version_info = tuple([int(x) for x in zmq.zmq_version().split(u'.')])
if (zmq_version_info < (3, 2)):
log.warning(u'You have a version of ZMQ less th... |
'Run pre flight checks. If anything in this method fails then the master
should not start up.'
| def _pre_flight(self):
| errors = []
critical_errors = []
try:
os.chdir(u'/')
except OSError as err:
errors.append(u'Cannot change to root directory ({0})'.format(err))
if self.opts.get(u'fileserver_verify_config', True):
fileserver = salt.fileserver.Fileserver(self.opts)
if (n... |
'Turn on the master server components'
| def start(self):
| self._pre_flight()
log.info(u"salt-master is starting as user '%s'", salt.utils.get_user())
enable_sigusr1_handler()
enable_sigusr2_handler()
self.__set_max_open_files()
with salt.utils.process.default_signals(signal.SIGINT, signal.SIGTERM):
SMaster.secrets[u'aes'] = {u'se... |
'Create a halite instance
:param dict hopts: The halite options'
| def __init__(self, hopts, log_queue=None):
| super(Halite, self).__init__(log_queue=log_queue)
self.hopts = hopts
|
'Fire up halite!'
| def run(self):
| salt.utils.appendproctitle(self.__class__.__name__)
halite.start(self.hopts)
|
'Create a request server
:param dict opts: The salt options dictionary
:key dict: The user starting the server and the AES key
:mkey dict: The user starting the server and the RSA key
:rtype: ReqServer
:returns: Request server'
| def __init__(self, opts, key, mkey, log_queue=None, secrets=None):
| super(ReqServer, self).__init__(log_queue=log_queue)
self.opts = opts
self.master_key = mkey
self.key = key
self.secrets = secrets
|
'Binds the reply server'
| def __bind(self):
| if (self.log_queue is not None):
salt.log.setup.set_multiprocessing_logging_queue(self.log_queue)
salt.log.setup.setup_multiprocessing_logging(self.log_queue)
if (self.secrets is not None):
SMaster.secrets = self.secrets
dfn = os.path.join(self.opts[u'cachedir'], u'.dfn')
if os.path.... |
'Start up the ReqServer'
| def run(self):
| self.__bind()
|
'Create a salt master worker process
:param dict opts: The salt options
:param dict mkey: The user running the salt master and the AES key
:param dict key: The user running the salt master and the RSA key
:rtype: MWorker
:return: Master worker'
| def __init__(self, opts, mkey, key, req_channels, name, **kwargs):
| kwargs[u'name'] = name
super(MWorker, self).__init__(**kwargs)
self.opts = opts
self.req_channels = req_channels
self.mkey = mkey
self.key = key
self.k_mtime = 0
|
'Bind to the local port'
| def __bind(self):
| if HAS_ZMQ:
zmq.eventloop.ioloop.install()
self.io_loop = LOOP_CLASS()
self.io_loop.make_current()
for req_channel in self.req_channels:
req_channel.post_fork(self._handle_payload, io_loop=self.io_loop)
try:
self.io_loop.start()
except (KeyboardInterrupt, SystemExit):
... |
'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\': \'test.ping\',
\'jid\': \'\',
\'key\': \'alsdkjfa.,malj... | @tornado.gen.coroutine
def _handle_payload(self, payload):
| key = payload[u'enc']
load = payload[u'load']
ret = {u'aes': self._handle_aes, u'clear': self._handle_clear}[key](load)
raise tornado.gen.Return(ret)
|
'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):
| log.trace(u'Clear payload received with command %s', load[u'cmd'])
if load[u'cmd'].startswith(u'__'):
return False
return (getattr(self.clear_funcs, load[u'cmd'])(load), {u'fun': u'send_clear'})
|
'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):
| if (u'cmd' not in data):
log.error(u'Received malformed command %s', data)
return {}
log.trace(u'AES payload received with command %s', data[u'cmd'])
if data[u'cmd'].startswith(u'__'):
return False
return self.aes_funcs.run_func(data[u'cmd'], data)
|
'Start a Master Worker'
| def run(self):
| salt.utils.appendproctitle(self.name)
self.clear_funcs = ClearFuncs(self.opts, self.key)
self.aes_funcs = AESFuncs(self.opts)
salt.utils.reinit_crypto()
self.__bind()
|
'Create a new AESFuncs
:param dict opts: The salt options
:rtype: AESFuncs
:returns: Instance for handling AES operations'
| def __init__(self, opts):
| self.opts = opts
self.event = salt.utils.event.get_master_event(self.opts, self.opts[u'sock_dir'], listen=False)
self.serial = salt.payload.Serial(opts)
self.ckminions = salt.utils.minions.CkMinions(opts)
self.local = salt.client.get_local_client(self.opts[u'conf_file'])
self.mminion = salt.mini... |
'Set the local file objects from the file server interface'
| def __setup_fileserver(self):
| self.fs_ = salt.fileserver.Fileserver(self.opts)
self._serve_file = self.fs_.serve_file
self._file_find = self.fs_._find_file
self._file_hash = self.fs_.file_hash
self._file_hash_and_stat = self.fs_.file_hash_and_stat
self._file_list = self.fs_.file_list
self._file_list_emptydirs = self.fs_.... |
'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 token can be verified.'
| def __verify_minion(self, id_, token):
| if (not salt.utils.verify.valid_id(self.opts, id_)):
return False
pub_path = os.path.join(self.opts[u'pki_dir'], u'minions', id_)
try:
with salt.utils.files.fopen(pub_path, u'r') as fp_:
minion_pub = fp_.read()
pub = RSA.importKey(minion_pub)
except (IOError, OSEr... |
'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 token can be verified.'
| def verify_minion(self, id_, token):
| return self.__verify_minion(id_, token)
|
'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):
| if (u'peer' not in self.opts):
return False
if (not isinstance(self.opts[u'peer'], dict)):
return False
if any(((key not in clear_load) for key in (u'fun', u'arg', u'tgt', u'ret', u'tok', u'id'))):
return False
if clear_load[u'fun'].startswith(u'publish.'):
return False
... |
'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 the load can be
verified. False if the load is inv... | def __verify_load(self, load, verify_keys):
| if any(((key not in load) for key in verify_keys)):
return False
if (u'tok' not in load):
log.error(u"Received incomplete call from %s for '%s', missing '%s'", load[u'id'], inspect_stack()[u'co_name'], u'tok')
return False
if (not self.__verify_minion(load[u'i... |
'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):
| load = self.__verify_load(load, (u'id', u'tok'))
if (load is False):
return {}
return self.masterapi._master_tops(load, skip_verify=True)
|
'Return the master options to the minion
:param dict load: A payload received from a minion
:rtype: dict
:return: The master options'
| def _master_opts(self, load):
| mopts = {}
file_roots = {}
envs = self._file_envs()
for saltenv in envs:
if (saltenv not in file_roots):
file_roots[saltenv] = []
mopts[u'file_roots'] = file_roots
mopts[u'top_file_merging_strategy'] = self.opts[u'top_file_merging_strategy']
mopts[u'env_order'] = self.opt... |
'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):
| load = self.__verify_load(load, (u'id', u'tgt', u'fun', u'tok'))
if (load is False):
return {}
else:
return self.masterapi._mine_get(load, skip_verify=True)
|
'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):
| load = self.__verify_load(load, (u'id', u'data', u'tok'))
if (load is False):
return {}
return self.masterapi._mine(load, skip_verify=True)
|
'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):
| load = self.__verify_load(load, (u'id', u'fun', u'tok'))
if (load is False):
return {}
else:
return self.masterapi._mine_delete(load)
|
'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):
| load = self.__verify_load(load, (u'id', u'tok'))
if (load is False):
return {}
else:
return self.masterapi._mine_flush(load, skip_verify=True)
|
'Allows minions to send files to the master, files are sent to the
master file cache'
| def _file_recv(self, load):
| if any(((key not in load) for key in (u'id', u'path', u'loc'))):
return False
if (not isinstance(load[u'path'], list)):
return False
if (not self.opts[u'file_recv']):
return False
if (not salt.utils.verify.valid_id(self.opts, load[u'id'])):
return False
file_recv_max_... |
'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):
| if any(((key not in load) for key in (u'id', u'grains'))):
return False
if (not salt.utils.verify.valid_id(self.opts, load[u'id'])):
return False
load[u'grains'][u'id'] = load[u'id']
pillar_dirs = {}
pillar = salt.pillar.get_pillar(self.opts, load[u'grains'], load[u'id'], load.get(u'... |
'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):
| load = self.__verify_load(load, (u'id', u'tok'))
if (load is False):
return {}
self.masterapi._minion_event(load)
self._handle_minion_event(load)
|
'Act on specific events from minions'
| def _handle_minion_event(self, load):
| id_ = load[u'id']
if (load.get(u'tag', u'') == u'_salt_error'):
log.error(u'Received minion error from [%s]: %s', id_, load[u'data'][u'message'])
for event in load.get(u'events', []):
event_data = event.get(u'data', {})
if (u'minions' in event_data):
jid = ... |
'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 payload'
| def _return(self, load):
| if (self.opts[u'require_minion_sign_messages'] and (u'sig' not in load)):
log.critical(u'_return: Master is requiring minions to sign their messages, but there is no signature in this payload from %s.', load[u'id'])
return False
if (u'sig' in... |
'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):
| if any(((key not in load) for key in (u'return', u'jid', u'id'))):
return None
if load.get(u'load'):
fstr = u'{0}.save_load'.format(self.opts[u'master_job_cache'])
self.mminion.returners[fstr](load[u'jid'], load[u'load'])
syndic_cache_path = os.path.join(self.opts[u'cachedir'], u'syn... |
'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):
| load = self.__verify_load(clear_load, (u'fun', u'arg', u'id', u'tok'))
if (load is False):
return {}
else:
return self.masterapi.minion_runner(clear_load)
|
'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):
| load = self.__verify_load(load, (u'jid', u'id', u'tok'))
if (load is False):
return {}
auth_cache = os.path.join(self.opts[u'cachedir'], u'publish_auth')
if (not os.path.isdir(auth_cache)):
os.makedirs(auth_cache)
jid_fn = os.path.join(auth_cache, str(load[u'jid']))
with salt.uti... |
'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 functions
The config will look l... | def minion_pub(self, clear_load):
| if (not self.__verify_minion_publish(clear_load)):
return {}
else:
return self.masterapi.minion_pub(clear_load)
|
'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 functions
The config will look l... | def minion_publish(self, clear_load):
| if (not self.__verify_minion_publish(clear_load)):
return {}
else:
return self.masterapi.minion_publish(clear_load)
|
'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):
| load = self.__verify_load(load, (u'id', u'tok'))
if (not self.opts.get(u'allow_minion_key_revoke', False)):
log.warning(u'Minion %s requested key revoke, but allow_minion_key_revoke is set to False', load[u'id'])
return load
if (load is False):
return lo... |
'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):
| if func.startswith(u'__'):
return ({}, {u'fun': u'send'})
if hasattr(self, func):
try:
start = time.time()
ret = getattr(self, func)(load)
log.trace(u'Master function call %s took %s seconds', func, (time.time() - start))
except Excep... |
'Send a master control function back to the runner system'
| def runner(self, clear_load):
| if (u'token' in clear_load):
token = self.loadauth.authenticate_token(clear_load)
if (not token):
return dict(error=dict(name=u'TokenAuthenticationError', message=u'Authentication failure of type "token" occurred.'))
if (self.opts[u'keep_acl_in_token'] and (u'auth_... |
'Send a master control function back to the wheel system'
| def wheel(self, clear_load):
| username = None
if (u'token' in clear_load):
token = self.loadauth.authenticate_token(clear_load)
if (not token):
return dict(error=dict(name=u'TokenAuthenticationError', message=u'Authentication failure of type "token" occurred.'))
if (self.opts[u'keep_acl_in_... |
'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):
| token = self.loadauth.mk_token(clear_load)
if (not token):
log.warning(u'Authentication failure of type "eauth" occurred.')
return u''
return token
|
'Return the name associated with a token or False if the token is invalid'
| def get_token(self, clear_load):
| if (u'token' not in clear_load):
return False
return self.loadauth.get_tok(clear_load[u'token'])
|
'This method sends out publications to the minions, it can only be used
by the LocalClient.'
| def publish(self, clear_load):
| extra = clear_load.get(u'kwargs', {})
publisher_acl = salt.acl.PublisherACL(self.opts[u'publisher_acl_blacklist'])
if (publisher_acl.user_is_blacklisted(clear_load[u'user']) or publisher_acl.cmd_is_blacklisted(clear_load[u'fun'])):
log.error(u'%s does not have permissions to run ... |
'Return a jid for this publication'
| def _prep_jid(self, clear_load, extra):
| passed_jid = (clear_load[u'jid'] if clear_load.get(u'jid') else None)
nocache = extra.get(u'nocache', False)
fstr = u'{0}.prep_jid'.format(self.opts[u'master_job_cache'])
try:
jid = self.mminion.returners[fstr](nocache=nocache, passed_jid=passed_jid)
except (KeyError, TypeError):
msg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.