Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def netstats():
'''
Return the network stats for this minion
CLI Example::
salt '*' status.netstats
'''
procf = '/proc/net/netstat'
if not os.path.isfile(procf):
return {}
stats = salt.utils.fopen(procf, 'r').read().splitlines()
ret = {}
headers = ['']
for line in stats:
if not line:
continue
comps = line.split()
if comps[0] == headers[0]:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = _number(comps[field])
rowname = headers[0].replace(':', '')
ret[rowname] = row
Execute the run in a dedicated process
'''
data = msg['pub']
fn_ = os.path.join(self.proc_dir, data['jid'])
self.opts['__ex_id'] = data['jid']
salt.utils.daemonize_if(self.opts)
salt.transport.jobber_stack = stack = self._setup_jobber_stack()
# set up return destination from source
src_estate, src_yard, src_share = msg['route']['src']
salt.transport.jobber_estate_name = src_estate
salt.transport.jobber_yard_name = src_yard
sdata = {'pid': os.getpid()}
sdata.update(data)
with salt.utils.fopen(fn_, 'w+b') as fp_:
fp_.write(self.serial.dumps(sdata))
ret = {'success': False}
function_name = data['fun']
if function_name in self.modules.value:
try:
func = self.modules.value[data['fun']]
args, kwargs = salt.minion.load_args_and_kwargs(
func,
salt.utils.args.parse_input(data['arg']),
data)
sys.modules[func.__module__].__context__['retcode'] = 0
executors = data.get('module_executors') or self.opts.get('module_executors', ['direct_call.get'])
if isinstance(executors, six.string_types):
executors = [executors]
elif not isinstance(executors, list) or not executors:
return file_hash(load, fnd)
# if we don't have a cache entry-- lets make one
ret['hsum'] = salt.utils.get_hash(path, __opts__['hash_type'])
cache_dir = os.path.dirname(cache_path)
# make cache directory if it doesn't exist
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
# save the cache object "hash:mtime"
if HAS_FCNTL:
with salt.utils.flopen(cache_path, 'w') as fp_:
fp_.write('{0}:{1}'.format(ret['hsum'], os.path.getmtime(path)))
fcntl.flock(fp_.fileno(), fcntl.LOCK_UN)
return ret
else:
with salt.utils.fopen(cache_path, 'w') as fp_:
fp_.write('{0}:{1}'.format(ret['hsum'], os.path.getmtime(path)))
return ret
raise CommandExecutionError(msg.format(config))
return 'change'
if not change and not present:
# The entry is new, add it to the end of the fstab
newline = '{0}\t\t{1}\t{2}\t{3}\t{4} {5}\n'.format(
device,
name,
fstype,
opts,
dump,
pass_num)
lines.append(newline)
try:
with salt.utils.fopen(config, 'w+') as ofile:
# The line was changed, commit it!
ofile.writelines(lines)
except (IOError, OSError):
raise CommandExecutionError(
'File not writable {0}'.format(
config
)
)
if present and not change:
# The right entry is already here
return 'present'
return 'new'
def __write_docker_compose(path, docker_compose):
'''
Write docker-compose to a temp directory
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if os.path.isdir(path) is False:
os.mkdir(path)
f = salt.utils.fopen(os.path.join(path, dc_filename), 'w') # pylint: disable=resource-leakage
if f:
f.write(docker_compose)
f.close()
else:
return __standardize_result(False,
'Could not write docker-compose file in {0}'.format(path),
None, None)
project = __load_project(path)
if isinstance(project, dict):
os.remove(os.path.join(path, dc_filename))
return project
return path
def token_cli(self, eauth, load):
'''
Create the token from the CLI and request the correct data to
authenticate via the passed authentication mechanism
'''
load['cmd'] = 'mk_token'
load['eauth'] = eauth
sreq = salt.payload.SREQ(
'tcp://{0[interface]}:{0[ret_port]}'.format(self.opts),
)
tdata = sreq.send('clear', load)
if 'token' not in tdata:
return tdata
try:
with salt.utils.fopen(self.opts['token_file'], 'w+') as fp_:
fp_.write(tdata['token'])
except (IOError, OSError):
pass
return tdata
else:
return ''
else:
dest = salt.utils.path_join(
self.opts['cachedir'],
'extrn_files',
env,
url_data.netloc,
url_data.path
)
destdir = os.path.dirname(dest)
if not os.path.isdir(destdir):
os.makedirs(destdir)
try:
with contextlib.closing(url_open(url)) as srcfp:
with salt.utils.fopen(dest, 'wb') as destfp:
shutil.copyfileobj(srcfp, destfp)
return dest
except HTTPError as ex:
raise MinionError('HTTP error {0} reading {1}: {3}'.format(
ex.code,
url,
*BaseHTTPServer.BaseHTTPRequestHandler.responses[ex.code]))
except URLError as ex:
raise MinionError('Error reading {0}: {1}'.format(url, ex.reason))
def _update_checksum(fname, target, checksum):
lines = []
compare_string = '{0}:{1}'.format(target, checksum)
if os.path.exists(fname):
with salt.utils.fopen(fname, 'r') as f:
lines = f.readlines()
with salt.utils.fopen(fname, 'w') as f:
f.write('{0}:{1}\n'.format(target, checksum))
for line in lines:
if line.startswith(target):
continue
f.write(line)
def _read_next_ac_chunk(clear=True):
'''
Read and remove the content of '_mgractionchains.conf' file. Return the parsed YAML.
'''
f_storage_filename = _get_ac_storage_filenamepath()
if not os.path.isfile(f_storage_filename):
return None
ret = None
try:
with salt.utils.fopen(f_storage_filename, "r") as f_storage:
ret = yaml.load(f_storage.read())
if clear:
os.remove(f_storage_filename)
return ret
except (IOError, yaml.scanner.ScannerError) as exc:
err_str = "Error processing YAML from '{0}': {1}".format(f_storage_filename, exc)
log.error(err_str)
raise CommandExecutionError(err_str)