Compare commits

..
Author SHA1 Message Date
Mike Reeves 3743173c88 Start the queue with Valkey settings and a longer stop timeout 2026-11-25 10:14:36 -05:00
35 changed files with 115 additions and 1333 deletions

No files matched your search

-2
View File
@@ -164,7 +164,6 @@ if [[ $EXCLUDE_FALSE_POSITIVE_ERRORS == 'Y' ]]; then
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|syncing rule" # false positive (rule sync log line includes rule name which can contain 'error')
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|request_unauthorized" # false positive (login failures to Hydra result in an 'error' log)
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|adding index lifecycle policy" # false positive (elasticsearch policy names contain 'error')
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|updating index lifecycle policy" # false positive (elasticsearch policy names contain 'error')
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|adding ingest pipeline" # false positive (elasticsearch ingest pipeline names contain 'error')
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|updating index template" # false positive (elasticsearch index or template names contain 'error')
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|updating component template" # false positive (elasticsearch index or template names contain 'error')
@@ -180,7 +179,6 @@ if [[ $EXCLUDE_FALSE_POSITIVE_ERRORS == 'Y' ]]; then
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|Static assets preprocessor only supports GET and HEAD requests" # expected WARN log lines indicating invalid auth header
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|respondError" # respondError is a function name, output via http middleware as standard request logging
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|GET /kibana/" # Ignore Kibana queries with triggered words
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|error-logs" # Elastic indexes can contain error-logs in their names, which can trigger false positives in log checks
fi
if [[ $EXCLUDE_KNOWN_ERRORS == 'Y' ]]; then
@@ -41,7 +41,6 @@
'logstash.node': 'logstash.stack_monitoring.node',
'logstash.node_cel': 'logstash.node',
'logstash.node_stats': 'logstash.stack_monitoring.node_stats',
'mqtt.traces': 'traces-mqtt.traces',
'synthetics.browser': 'synthetics-browser',
'synthetics.browser_network': 'synthetics-browser.network',
'synthetics.browser_screenshot': 'synthetics-browser.screenshot',
+1 -1
View File
@@ -1,7 +1,7 @@
elasticsearch:
enabled: false
esheap: '600m'
version: 9.4.10
version: 9.4.8
index_clean: true
data_retention_method: DLM
vm:
-5
View File
@@ -1,5 +1,4 @@
{% from 'vars/globals.map.jinja' import GLOBALS %}
{% from 'telegraf/map.jinja' import INFLUX_RETIRED %}
{% if GLOBALS.role == 'so-eval' %}
{% set NODE_CONTAINERS = [
@@ -110,7 +109,3 @@
{% set NODE_CONTAINERS = [] %}
{% endif %}
{% if INFLUX_RETIRED and 'so-influxdb' in NODE_CONTAINERS %}
{% do NODE_CONTAINERS.remove('so-influxdb') %}
{% endif %}
-10
View File
@@ -1,6 +1,5 @@
{% from 'vars/globals.map.jinja' import GLOBALS %}
{% from 'docker/docker.map.jinja' import DOCKERMERGED %}
{% from 'telegraf/map.jinja' import INFLUX_RETIRED %}
{% import_yaml 'firewall/defaults.yaml' as FIREWALL_DEFAULT %}
{# add our ip to self #}
@@ -61,12 +60,3 @@
{% endif %}
{% set FIREWALL_MERGED = salt['pillar.get']('firewall', FIREWALL_DEFAULT.firewall, merge=True) %}
{# filtered after the merge so portgroup lists saved in Configuration lose influxdb too #}
{% if INFLUX_RETIRED and (role.startswith('manager') or role in ['eval', 'standalone', 'import']) %}
{% for hostgroup in FIREWALL_MERGED.role[role].chain['DOCKER-USER'].hostgroups.values() %}
{% if 'influxdb' in hostgroup.get('portgroups', []) %}
{% do hostgroup.update({'portgroups': hostgroup.portgroups | reject('equalto', 'influxdb') | list}) %}
{% endif %}
{% endfor %}
{% endif %}
+3 -3
View File
@@ -8,10 +8,10 @@ influxdb:
flux-log-enabled: false
hardening-enabled: true
http-bind-address: :8086
http-idle-timeout: 0s
http-idle-timeout: 0
http-read-header-timeout: 10s
http-read-timeout: 0s
http-write-timeout: 0s
http-read-timeout: 0
http-write-timeout: 0
influxql-max-select-buckets: 0
influxql-max-select-point: 0
influxql-max-select-series: 0
+1 -4
View File
@@ -4,12 +4,9 @@
# Elastic License 2.0.
{% from 'influxdb/map.jinja' import INFLUXMERGED %}
{% from 'telegraf/map.jinja' import INFLUX_RETIRED %}
include:
{% if INFLUX_RETIRED %}
- influxdb.retired
{% elif INFLUXMERGED.enabled %}
{% if INFLUXMERGED.enabled %}
- influxdb.enabled
{% else %}
- influxdb.disabled
-31
View File
@@ -1,31 +0,0 @@
# Copyright Security Onion Solutions LLC and/or licensed to Security Onion Solutions LLC under one
# or more contributor license agreements. Licensed under the Elastic License 2.0 as shown at
# https://securityonion.net/license; you may not use this file except in compliance with the
# Elastic License 2.0.
{% from 'allowed_states.map.jinja' import allowed_states %}
{% if sls.split('.')[0] in allowed_states %}
include:
- influxdb.disabled
influxdb_data_purged:
file.directory:
- name: /nsm/influxdb
- clean: True
- require:
- docker_container: so-influxdb
influxdb_conf_purged:
file.absent:
- name: /opt/so/conf/influxdb
- require:
- docker_container: so-influxdb
{% else %}
{{sls}}_state_not_allowed:
test.fail_without_changes:
- name: {{sls}}_state_not_allowed
{% endif %}
+4 -4
View File
@@ -1,6 +1,6 @@
influxdb:
enabled:
description: Enables the grid metrics collection storage system. Security Onion grid health monitoring requires this process to remain enabled. WARNING - Disabling the process is unsupported, and will cause unexpected results. This setting has no effect when telegraf.output is POSTGRES.
description: Enables the grid metrics collection storage system. Security Onion grid health monitoring requires this process to remain enabled. WARNING - Disabling the process is unsupported, and will cause unexpected results.
forcedType: bool
helpLink: influxdb
config:
@@ -42,17 +42,17 @@ influxdb:
advanced: True
helpLink: influxdb
http-idle-timeout:
description: Keep-alive timeout while a connection waits for new requests. A value of 0s is the same as no timeout enforced.
description: Keep-alive timeout while a connection waits for new requests. A value of 0 is the same as no timeout enforced.
global: True
advanced: True
helpLink: influxdb
http-read-header-timeout:
description: The duration to wait for a request header before closing the connection. A value of 0s is the same as no timeout enforced.
description: The duration to wait for a request header before closing the connection. A value of 0 is the same as no timeout enforced.
global: True
advanced: True
helpLink: influxdb
http-read-timeout:
description: The duration to wait for the request to be fully read before closing the connection. A value of 0s is the same as no timeout enforced.
description: The duration to wait for the request to be fully read before closing the connection. A value of 0 is the same as no timeout enforced.
global: True
advanced: True
helpLink: influxdb
+1 -1
View File
@@ -128,7 +128,7 @@ lookup_org_id_with_wait() {
wait=10
while [[ $attempts -lt $max_attempts ]]; do
response=$(request orgs?org=Security+Onion)
oid=$(echo "$response" | jq -r ".orgs[]? | select(.name == \"Security Onion\").id")
oid=$(echo "$response" | jq -r ".orgs[] | select(.name == \"Security Onion\").id")
if [[ -z $oid ]]; then
attempts=$((attempts+1))
log "Server does not appear to be running or fully initialized - will try again in $wait seconds ($attempts / $max_attempts)"
+1 -1
View File
@@ -22,7 +22,7 @@ kibana:
- default
- file
migrations:
discardCorruptObjects: "9.4.10"
discardCorruptObjects: "9.4.8"
telemetry:
enabled: False
xpack:
+21 -196
View File
@@ -16,11 +16,7 @@ For each intent file under /opt/so/state/push_pending/*.json whose last_touch
is older than debounce_seconds, this script:
* concatenates the actions lists from every ready intent
* dedupes by (state or __highstate__, tgt, tgt_type)
* narrows each target to minions that have completed a highstate
* keeps the part of an action that would reach a node still in its first highstate in
push_pending/pending_<id>.json, which drains like any other intent once that highstate completes
* drops actions whose target matches no accepted minion (e.g. a role with no nodes yet)
* holds everything for a later pass while salt-master has only just started
* dispatches a single `salt-run state.orchestrate orch.push_batch --async`
with the deduped actions list passed as pillar kwargs
* deletes the contributed intent files on successful dispatch
@@ -50,25 +46,11 @@ PENDING_DIR = '/opt/so/state/push_pending'
LOCK_FILE = os.path.join(PENDING_DIR, '.lock')
LOG_FILE = '/opt/so/log/salt/so-push-drainer.log'
MASTER_CONFIG = '/etc/salt/master'
MASTER_PIDFILE = '/var/run/salt-master.pid'
MINION_KEYS_DIR = '/etc/salt/pki/master/minions'
MAX_PATHS = 20
# Minions rejoin a restarted master's publisher up to ~22s after it returns (zmq reconnect interval
# plus jitter, each up to recon_default + recon_max) and a job published before then reaches nobody.
# Doubled to allow for a slow master start.
MASTER_SETTLE_SECONDS = 45
DISPATCHED_DIR = '/opt/so/state/push_dispatched'
HIGHSTATE_SENTINEL = '__highstate__'
# Grain written by setup and removed by salt.lasthighstate at the end of the node's first highstate.
PENDING_GRAIN = 'first_highstate_pending'
# Node ids from the master's cache go into kept intent file names and targets.
ID_RE = re.compile(r'[A-Za-z0-9._-]{1,253}')
RESULT_CHECK_DELAY = 30
RESULT_RECHECK_MAX = 300
RESULT_MAX_AGE = 7200
@@ -78,8 +60,6 @@ TEXT_LIMIT = 500
# Lead-in salt puts on the comment of an orchestration step that raised.
STEP_RAISED = 'An exception occurred in this state:'
NO_RETURN = 'no return received'
# salt-run --async reports the jid only in a log line (stderr by default).
JID_RE = re.compile(r'salt/run/(\d{20})')
@@ -137,134 +117,27 @@ def _dedupe_actions(actions):
return deduped
def _skip_pending(action):
"""Narrows a compound target to minions that have completed a highstate. A newly accepted node matches
its role's targets before orch.deploy_newnode has highstated it, and a single state fails there."""
if action.get('tgt_type', 'compound') != 'compound':
return action
return dict(action, tgt='( {} ) and not G@{}:True'.format(action.get('tgt'), PENDING_GRAIN))
def _ckminions():
return salt.utils.minions.CkMinions(salt.config.master_config(MASTER_CONFIG))
def _pending_minions(ckminions, log):
try:
return set(ckminions.check_minions('G@{}:True'.format(PENDING_GRAIN), 'compound').get('minions') or [])
except Exception as exc:
log.warning('cannot list nodes still in their first highstate; keeping no pushes for them: %s', exc)
return set()
def _targeted(actions, log):
"""Returns (targeted, kept). Drops actions whose target matches no accepted minion (e.g. a role with no
nodes yet), which the orchestration would otherwise report as failed with 'No minions responded'. The part
of a compound action that would reach a node still in its first highstate is returned in kept, by node id,
narrowed to that node, so it can be applied once that highstate completes."""
"""Drops actions whose target matches no accepted minion (e.g. a role with no nodes yet), which
the orchestration would otherwise report as failed with 'No minions responded'."""
try:
ckminions = _ckminions()
ckminions = salt.utils.minions.CkMinions(salt.config.master_config(MASTER_CONFIG))
except Exception:
log.exception('cannot load master config; dispatching without checking targets')
return [_skip_pending(action) for action in actions], {}
pending = _pending_minions(ckminions, log)
return actions
targeted = []
kept = {}
for action in actions:
narrowed = _skip_pending(action)
tgt_type = action.get('tgt_type', 'compound')
name = 'highstate' if action.get('highstate') else action.get('state')
try:
matched = ckminions.check_minions(narrowed['tgt'], tgt_type).get('minions')
unwrapped = []
if pending and tgt_type == 'compound':
unwrapped = ckminions.check_minions(action['tgt'], tgt_type).get('minions')
matched = ckminions.check_minions(action['tgt'], action.get('tgt_type', 'compound')).get('minions')
except Exception:
log.exception('cannot resolve tgt=%s; dispatching it anyway', narrowed.get('tgt'))
matched, unwrapped = True, []
held = False
for minion in sorted(pending.intersection(unwrapped or [])):
if not ID_RE.fullmatch(minion):
log.warning('not keeping %s for %r: not a valid node id', name, minion)
continue
kept.setdefault(minion, []).append(
dict(action, tgt='L@{} and ( {} )'.format(minion, action['tgt']), tgt_type='compound'))
held = True
log.exception('cannot resolve tgt=%s; dispatching it anyway', action.get('tgt'))
matched = True
if matched:
targeted.append(narrowed)
elif not held:
log.info('skipping %s: no minions match tgt=%s', name, action['tgt'])
return targeted, kept
def _kept_path(node):
return os.path.join(PENDING_DIR, 'pending_{}.json'.format(node))
def _keep_for_pending(kept, paths, log):
"""Merges each node's kept actions into its pending_<id>.json. The caller already holds the lock, which
flock would not grant a second time. Returns False if any write failed."""
now = time.time()
written = True
for node, actions in kept.items():
path = _kept_path(node)
intent = _read_intent(path, log) if os.path.exists(path) else {}
if not isinstance(intent, dict):
intent = {}
known = intent.get('paths') or []
intent.update(
actions=_dedupe_actions((intent.get('actions') or []) + actions),
pending=node,
last_touch=now,
paths=(known + [p for p in paths if p not in known])[-MAX_PATHS:],
)
intent.setdefault('first_touch', now)
try:
tmp_path = path + '.tmp'
with open(tmp_path, 'w') as f:
json.dump(intent, f)
os.rename(tmp_path, path)
except (OSError, ValueError) as exc:
log.error('cannot keep pushes for %s until its first highstate completes: %s', node, exc)
written = False
continue
prefix = 'L@{} and ( '.format(node)
for action in actions:
tgt = action['tgt']
if tgt.startswith(prefix) and tgt.endswith(' )'):
tgt = tgt[len(prefix):-len(' )')]
log.info('push kept for %s until its first highstate completes: %s tgt=%s', node,
'highstate' if action.get('highstate') else action.get('state'), tgt)
return written
def _still_pending(ckminions, ids, log):
"""Ids whose first highstate has not completed. A node with no cache entry has not compiled pillar yet."""
pending = set()
for node in ids:
try:
data = ckminions.cache.fetch('minions/{}'.format(node), 'data')
except Exception as exc:
log.warning('cannot read the cached grains of %s; holding its kept pushes: %s', node, exc)
pending.add(node)
continue
grains = data.get('grains') if isinstance(data, dict) else None
if not isinstance(grains, dict) or PENDING_GRAIN in grains:
pending.add(node)
return pending
def _master_settling(now):
"""True while salt-master started less than MASTER_SETTLE_SECONDS ago. salt-master writes its pidfile
when it starts, so the file's mtime is the master's start time. Minions take up to ~22s to rejoin a
restarted master's publisher and a job published before then reaches nobody, so dispatch is held;
held intents stay in push_pending and are drained on a later pass. A missing or unreadable pidfile
returns False: the master is then normally not running, so _dispatch fails and keeps the intents."""
try:
age = now - os.path.getmtime(MASTER_PIDFILE)
except OSError:
return False
return 0 <= age < MASTER_SETTLE_SECONDS
targeted.append(action)
else:
log.info('skipping %s: no minions match tgt=%s',
'highstate' if action.get('highstate') else action.get('state'), action.get('tgt'))
return targeted
def _dispatch(actions, log):
@@ -348,10 +221,6 @@ def _lookup_jid(jid, log):
def _minion_failure(minion_ret):
# What salt.state records for a minion it stopped waiting on: no reply to a saltutil.find_job
# poll within gather_job_timeout, though the state run may still be queued or running.
if minion_ret == {}:
return NO_RETURN
if isinstance(minion_ret, dict):
return '; '.join(
'{}: {}'.format(state.get('__id__', state_key), _trim(state.get('comment', '')))
@@ -414,21 +283,11 @@ def _failed_steps(ret):
return steps
def _lost_track(step):
changes = step.get('changes')
minion_rets = changes.get('ret') if isinstance(changes, dict) else None
if not isinstance(minion_rets, dict):
return False
failed = [text for text in map(_minion_failure, minion_rets.values()) if text]
return bool(failed) and all(text == NO_RETURN for text in failed)
def _result_unknown(ret):
# A step that raised (e.g. salt-master restarted while it waited on a queued state run) or
# stopped waiting never collected the minion's return, so the state run may still have completed.
# A step that raised (e.g. salt-master restarted while it waited on a queued state run)
# never collected the minion's return, so the state run may still have completed.
steps = _failed_steps(ret)
return bool(steps) and all(
str(step.get('comment', '')).startswith(STEP_RAISED) or _lost_track(step) for step in steps)
return bool(steps) and all(str(step.get('comment', '')).startswith(STEP_RAISED) for step in steps)
def _recheck_delay(age):
@@ -528,39 +387,18 @@ def main():
now = time.time()
ready = []
skipped = 0
held = 0
broken = []
for path in intent_files:
intent = _read_intent(path, log)
if not isinstance(intent, dict):
broken.append(path)
continue
node = intent.get('pending')
if node is not None and not (isinstance(node, str) and ID_RE.fullmatch(node)):
log.warning('removing kept intent %s: %r is not a valid node id', path, node)
broken.append(path)
continue
if node is not None and not os.path.exists(os.path.join(MINION_KEYS_DIR, node)):
log.info('removing kept pushes for %s: its key is no longer accepted', node)
broken.append(path)
continue
last_touch = intent.get('last_touch', 0)
if now - last_touch < debounce_seconds:
skipped += 1
continue
ready.append((path, intent))
kept_nodes = {intent['pending'] for _, intent in ready if intent.get('pending') is not None}
if kept_nodes:
try:
still_pending = _still_pending(_ckminions(), kept_nodes, log)
except Exception as exc:
log.warning('cannot load master config; holding kept pushes: %s', exc)
still_pending = kept_nodes
waiting = {path for path, intent in ready if intent.get('pending') in still_pending}
held = len(waiting)
ready = [(path, intent) for path, intent in ready if path not in waiting]
for path in broken:
try:
os.unlink(path)
@@ -568,13 +406,8 @@ def main():
pass
if not ready:
if skipped or held:
log.debug('no ready intents (%d still in debounce window, %d for nodes still in their first highstate)',
skipped, held)
return 0
if _master_settling(now):
log.info('salt-master just started; holding %d intent(s) until minions reconnect', len(ready))
if skipped:
log.debug('no ready intents (%d still in debounce window)', skipped)
return 0
combined_actions = []
@@ -602,32 +435,24 @@ def main():
'draining %d intent(s): %d action(s) after dedupe (raw=%d), '
'debounce_duration=%.1fs, paths=%s',
len(ready), len(deduped), len(combined_actions),
debounce_duration, all_paths[:MAX_PATHS],
debounce_duration, all_paths[:20],
)
for action in deduped:
log.info('action: %s tgt=%s', 'highstate' if action.get('highstate') else action.get('state'),
action.get('tgt'))
targeted, kept = _targeted(deduped, log)
if kept and not _keep_for_pending(kept, all_paths, log):
log.warning('cannot keep pushes for nodes still in their first highstate; '
'leaving intent files in place for retry')
return 1
written = {_kept_path(node) for node in kept}
targeted = _targeted(deduped, log)
if targeted:
jid = _dispatch(targeted, log)
if jid is None:
log.warning('dispatch failed; leaving intent files in place for retry')
return 1
if jid:
_record_dispatch(jid, targeted, all_paths[:MAX_PATHS], log)
elif not kept:
_record_dispatch(jid, targeted, all_paths[:20], log)
else:
log.info('no action matches a minion; nothing to dispatch')
for path, _ in ready:
if path in written:
continue
try:
os.unlink(path)
except OSError:
+14 -574
View File
@@ -3,18 +3,14 @@
# https://securityonion.net/license; you may not use this file except in compliance with the
# Elastic License 2.0.
import errno
import fcntl
import importlib.util
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from importlib.machinery import SourceFileLoader
@@ -38,8 +34,6 @@ JID = '20260930171554259426'
ASYNC_STDERR = ('[WARNING ] Running in asynchronous mode. Results of this execution may be collected '
'by attaching to the master event bus or by examining the master job cache, if '
'configured. This execution is running under tag salt/run/{}\n'.format(JID))
NOT_PENDING = ' and not G@first_highstate_pending:True'
PENDING_TGT = 'G@first_highstate_pending:True'
CONFLICT = ('The function "state.sls" is running as PID 372218 and was started at '
'2026, Sep 30 17:15:40.466233 with jid 20260930171540466233')
@@ -94,22 +88,6 @@ RAISED_RET = _orch_ret(dict(REFRESH_STEP, **{
},
}), success=False)
LOST_RET = _orch_ret(dict(REFRESH_STEP, **{
'salt_|-apply_soc_1_|-apply_soc_1_|-state': {
'__id__': 'apply_soc_1', 'result': False,
'changes': {'out': 'highstate', 'ret': {'manager_standalone': {}}},
'comment': 'Run failed on minions: manager_standalone',
},
}), success=False)
LOST_AND_FAILED_RET = _orch_ret({
'salt_|-apply_soc_1_|-apply_soc_1_|-state': {
'__id__': 'apply_soc_1', 'result': False,
'changes': {'out': 'highstate', 'ret': {'manager_standalone': {}, 'sensor1_sensor': [CONFLICT]}},
'comment': 'Run failed on minions: manager_standalone, sensor1_sensor',
},
}, success=False)
SUCCESS_RET = _orch_ret(dict(REFRESH_STEP, **{
'salt_|-apply_telegraf_1_|-apply_telegraf_1_|-state': {
'__id__': 'apply_telegraf_1', 'result': True,
@@ -221,17 +199,6 @@ class TestHelpers(DrainerTestCase):
drainer._unlink(self.tmpdir, self.log)
self.log.exception.assert_called_once()
def test_master_settling(self):
pidfile = os.path.join(self.tmpdir, 'salt-master.pid')
now = time.time()
with patch.object(drainer, 'MASTER_PIDFILE', pidfile):
self.assertFalse(drainer._master_settling(now))
self.write_json(self.tmpdir, 'salt-master.pid', '1100')
for age, settling in ((0, True), (drainer.MASTER_SETTLE_SECONDS - 1, True),
(drainer.MASTER_SETTLE_SECONDS, False), (-60, False)):
os.utime(pidfile, (now - age, now - age))
self.assertIs(drainer._master_settling(now), settling, age)
class TestDispatch(DrainerTestCase):
@@ -298,13 +265,6 @@ class TestResults(DrainerTestCase):
self.assertEqual(drainer._minion_failure('Rendering SLS failed'), 'Rendering SLS failed')
self.assertEqual(drainer._minion_failure(True), '')
self.assertEqual(drainer._minion_failure({'a': {'result': True}}), '')
self.assertEqual(drainer._minion_failure({}), drainer.NO_RETURN)
def test_orch_failures_lost(self):
self.assertEqual(drainer._orch_failures(LOST_RET), [
'apply_soc_1: Run failed on minions: manager_standalone',
'manager_standalone: no return received',
])
def test_orch_failures_conflict(self):
failures = drainer._orch_failures(CONFLICT_RET)
@@ -348,17 +308,7 @@ class TestResults(DrainerTestCase):
def test_result_unknown(self):
self.assertTrue(drainer._result_unknown(RAISED_RET))
self.assertTrue(drainer._result_unknown(LOST_RET))
changed = json.loads(json.dumps(LOST_RET))
changed[MASTER]['return']['data'][MASTER]['salt_|-apply_soc_1_|-apply_soc_1_|-state']['changes']['ret'][
'sensor1_sensor'] = {'file_|-a_|-a_|-managed': {'result': True, 'changes': {'diff': 'x'}}}
self.assertTrue(drainer._result_unknown(changed))
odd = _orch_ret({'salt_|-apply_soc_1_|-apply_soc_1_|-state': {
'__id__': 'apply_soc_1', 'result': False, 'changes': 'Run failed', 'comment': 'Run failed on minions',
}}, success=False)
self.assertFalse(drainer._result_unknown(odd))
for ret in (CONFLICT_RET, STATE_FAIL_RET, SUCCESS_RET, LOST_AND_FAILED_RET, ['No minions matched'],
{MASTER: 'odd'},
for ret in (CONFLICT_RET, STATE_FAIL_RET, SUCCESS_RET, ['No minions matched'], {MASTER: 'odd'},
{MASTER: {'return': {'data': {MASTER: ['Rendering SLS failed']}}, 'success': False}}):
self.assertFalse(drainer._result_unknown(ret), ret)
mixed = _orch_ret(dict(RAISED_RET[MASTER]['return']['data'][MASTER],
@@ -400,21 +350,6 @@ class TestResults(DrainerTestCase):
self.assertIn('AuthenticationError: Authentication error occurred.', self.logged('warning'))
self.assertNotIn('6_unknown', self.logged('error'))
def test_check_dispatched_lost(self):
now = time.time()
results = {'1_lost': LOST_RET, '2_lost_and_failed': LOST_AND_FAILED_RET}
paths = [self.record(jid, 60, now) for jid in results]
with patch.object(drainer, '_lookup_jid', side_effect=lambda jid, log: results[jid]):
drainer._check_dispatched(self.log, now)
for path in paths:
self.assertFalse(os.path.exists(path), path)
self.assertIn('push result unknown jid=1_lost', self.logged('warning'))
self.assertIn('manager_standalone: no return received', self.logged('warning'))
self.assertNotIn('1_lost', self.logged('error'))
self.assertIn('push failed jid=2_lost_and_failed', self.logged('error'))
self.assertIn('is running as PID 372218', self.logged('error'))
def test_check_dispatched_survives_bad_result(self):
now = time.time()
bad = self.record('1_bad', 60, now)
@@ -496,19 +431,8 @@ class TestTargeted(DrainerTestCase):
self.CkMinions = patcher.start()
self.addCleanup(patcher.stop)
def test_skip_pending(self):
self.assertEqual(drainer._skip_pending({'state': 'soc', 'tgt': 'G@role:so-eval or G@role:so-manager'}),
{'state': 'soc', 'tgt': '( G@role:so-eval or G@role:so-manager )' + NOT_PENDING})
self.assertEqual(drainer._skip_pending({'highstate': True, 'tgt': '*', 'tgt_type': 'compound'}),
{'highstate': True, 'tgt': '( * )' + NOT_PENDING, 'tgt_type': 'compound'})
listed = {'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'}
self.assertEqual(drainer._skip_pending(listed), listed)
def test_drops_unmatched(self):
sensor = '( G@role:so-sensor )' + NOT_PENDING
heavynode = '( G@role:so-heavynode )' + NOT_PENDING
idh = '( G@role:so-idh )' + NOT_PENDING
matches = {sensor: ['sensor_sensor'], 'manager_manager': ['manager_manager']}
matches = {'G@role:so-sensor': ['sensor_sensor'], 'manager_manager': ['manager_manager']}
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {'minions': matches.get(tgt, [])}
actions = [
{'state': 'strelka', 'tgt': 'G@role:so-sensor'},
@@ -516,503 +440,30 @@ class TestTargeted(DrainerTestCase):
{'highstate': True, 'tgt': 'G@role:so-idh'},
{'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'},
]
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'strelka', 'tgt': sensor}, actions[3]], {}))
self.assertEqual(drainer._targeted(actions, self.log), [actions[0], actions[3]])
self.CkMinions.assert_called_once()
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
(PENDING_TGT, 'compound'), (sensor, 'compound'), (heavynode, 'compound'), (idh, 'compound'),
('manager_manager', 'list'),
('G@role:so-sensor', 'compound'), ('G@role:so-heavynode', 'compound'),
('G@role:so-idh', 'compound'), ('manager_manager', 'list'),
])
info = self.logged('info')
self.assertIn('skipping suricata: no minions match tgt=G@role:so-heavynode', info)
self.assertIn('skipping highstate: no minions match tgt=G@role:so-idh', info)
self.assertNotIn('strelka', info)
def test_list_target_unmatched(self):
self.ckminions.check_minions.return_value = {'minions': []}
actions = [{'state': 'soc', 'tgt': 'gone_manager', 'tgt_type': 'list'}]
self.assertEqual(drainer._targeted(actions, self.log), ([], {}))
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
(PENDING_TGT, 'compound'), ('gone_manager', 'list'),
])
info = self.logged('info')
self.assertIn('skipping soc: no minions match tgt=gone_manager', info)
self.assertNotIn('first highstate', info)
def test_narrowed_match_checks_once(self):
narrowed = '( G@role:so-sensor )' + NOT_PENDING
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {
'minions': [] if tgt == PENDING_TGT else ['sensor_sensor']}
actions = [{'state': 'suricata', 'tgt': 'G@role:so-sensor'}]
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'suricata', 'tgt': narrowed}], {}))
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
(PENDING_TGT, 'compound'), (narrowed, 'compound'),
])
def test_pending_set_empty_no_extra_calls(self):
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {
'minions': [] if tgt == PENDING_TGT else ['sensor_sensor']}
actions = [
{'state': 'suricata', 'tgt': 'G@role:so-sensor'},
{'highstate': True, 'tgt': '*'},
{'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'},
]
targeted, kept = drainer._targeted(actions, self.log)
self.assertEqual(len(targeted), 3)
self.assertEqual(kept, {})
tgts = [c.args[0] for c in self.ckminions.check_minions.call_args_list]
self.assertEqual(tgts.count(PENDING_TGT), 1)
self.assertEqual(len(tgts), 1 + len(actions))
self.assertNotIn('G@role:so-sensor', tgts)
def test_list_target_not_kept(self):
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {'minions': ['manager_manager']}
actions = [{'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'}]
self.assertEqual(drainer._targeted(actions, self.log), (actions, {}))
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
(PENDING_TGT, 'compound'), ('manager_manager', 'list'),
])
def test_original_check_error_keeps_action(self):
narrowed = '( G@role:so-sensor )' + NOT_PENDING
results = {PENDING_TGT: {'minions': ['sensor_new']}, narrowed: {'minions': []}}
def check(tgt, tgt_type):
if tgt not in results:
raise RuntimeError('boom')
return results[tgt]
self.ckminions.check_minions.side_effect = check
actions = [{'state': 'suricata', 'tgt': 'G@role:so-sensor'}]
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'suricata', 'tgt': narrowed}], {}))
self.log.exception.assert_called_once()
def test_master_config_error_keeps_actions(self):
actions = [{'state': 'soc', 'tgt': '*'}]
with patch.object(drainer.salt.config, 'master_config', side_effect=OSError('no config')):
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'soc', 'tgt': '( * )' + NOT_PENDING}], {}))
self.assertEqual(drainer._targeted(actions, self.log), actions)
self.log.exception.assert_called_once()
self.CkMinions.assert_not_called()
def test_check_error_keeps_action(self):
actions = [{'state': 'soc', 'tgt': 'G@role:'}]
self.ckminions.check_minions.side_effect = RuntimeError('bad target')
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'soc', 'tgt': '( G@role: )' + NOT_PENDING}], {}))
self.assertEqual(drainer._targeted(actions, self.log), actions)
self.log.exception.assert_called_once()
def test_pending_minions_error(self):
self.ckminions.check_minions.side_effect = RuntimeError('cache unavailable')
self.assertEqual(drainer._pending_minions(self.ckminions, self.log), set())
self.assertIn('cannot list nodes still in their first highstate', self.logged('warning'))
self.assertIn('cache unavailable', self.logged('warning'))
def test_still_pending(self):
cache = {'minions/a': {'grains': {drainer.PENDING_GRAIN: True}}, 'minions/b': {'grains': {'role': 'so-sensor'}},
'minions/c': {}}
self.ckminions.cache.fetch.side_effect = lambda bank, key: cache[bank]
self.assertEqual(drainer._still_pending(self.ckminions, {'a', 'b', 'c'}, self.log), {'a', 'c'})
self.assertEqual({c.args[1] for c in self.ckminions.cache.fetch.call_args_list}, {'data'})
self.log.warning.assert_not_called()
def test_still_pending_lookup_error(self):
self.ckminions.cache.fetch.side_effect = OSError('cache read failed')
self.assertEqual(drainer._still_pending(self.ckminions, {'a'}, self.log), {'a'})
self.assertIn('cannot read the cached grains of a', self.logged('warning'))
class FakeCkMinions:
"""Evaluates the compound targets the drainer builds against a fixed set of role targets."""
def __init__(self):
self.targets = {}
self.accepted = set()
self.pending = set()
self.grains = {}
self.fetch_error = None
self.cache = MagicMock()
self.cache.fetch.side_effect = self.fetch
def fetch(self, bank, key):
if self.fetch_error:
raise self.fetch_error
node = bank.split('/', 1)[1]
return {'grains': self.grains[node]} if node in self.grains else {}
def match(self, tgt):
# Salt's greedy matching: an accepted minion with no cached grains matches any grain target.
greedy = self.accepted - set(self.grains) if tgt.startswith('G@') else set()
if tgt == PENDING_TGT:
return self.pending | greedy
wrapped = re.fullmatch(r'\( (.*) \)' + re.escape(NOT_PENDING), tgt)
if wrapped:
return self.match(wrapped.group(1)) - self.match(PENDING_TGT)
narrowed = re.fullmatch(r'L@(\S+) and \( (.*) \)', tgt)
if narrowed:
return {narrowed.group(1)} & self.match(narrowed.group(2))
return set(self.targets.get(tgt, [])) | greedy
def check_minions(self, tgt, tgt_type='compound'):
return {'minions': sorted(self.match(tgt))}
def pend(self, *nodes):
for node in nodes:
self.pending.add(node)
self.grains[node] = {'role': 'so-sensor', drainer.PENDING_GRAIN: True}
def release(self, *nodes):
for node in nodes:
self.pending.discard(node)
self.grains[node] = {'role': 'so-sensor'}
SURICATA = {'state': 'suricata', 'tgt': 'G@role:so-sensor'}
def _kept_copy(node, action):
return dict(action, tgt='L@{} and ( {} )'.format(node, action['tgt']), tgt_type='compound')
class TestKeptPushes(DrainerTestCase):
def setUp(self):
super().setUp()
self.ck = FakeCkMinions()
self.ck.targets = {'G@role:so-sensor': ['a', 'b', 'c'], 'G@role:so-searchnode': ['s'], '*': ['a', 'b', 'c', 's']}
self.ck.release('a', 'b', 'c', 's')
self.keys = os.path.join(self.tmpdir, 'keys')
os.makedirs(self.keys)
for node in ('a', 'b', 'c', 's'):
self.accept(node)
self.cfg = {'enabled': True, 'debounce_seconds': 30}
self.run = MagicMock(return_value=MagicMock(stdout='', stderr=ASYNC_STDERR))
for target, name, kwargs in (
(drainer.salt.utils.minions, 'CkMinions', {'return_value': self.ck}),
(drainer.subprocess, 'run', {'new': self.run}),
(drainer, 'MINION_KEYS_DIR', {'new': self.keys}),
(drainer, '_make_logger', {'return_value': self.log}),
(drainer, '_load_push_cfg', {'side_effect': lambda: self.cfg}),
(drainer, '_check_dispatched', {}),
(drainer, '_master_settling', {'return_value': False}),
):
patcher = patch.object(target, name, **kwargs)
patcher.start()
self.addCleanup(patcher.stop)
def accept(self, node):
self.write_json(self.keys, node, '')
self.ck.accepted.add(node)
def source(self, actions, name='pillar_suricata.json', paths=None):
now = time.time()
return self.write_json(self.pending, name, {
'first_touch': now - 65, 'last_touch': now - 60, 'actions': actions,
'paths': paths or ['audit:suricata.config'],
})
def kept_path(self, node):
return os.path.join(self.pending, 'pending_{}.json'.format(node))
def kept(self, node):
with open(self.kept_path(node)) as f:
return json.load(f)
def age(self, node, seconds=60):
intent = self.kept(node)
intent['last_touch'] -= seconds
self.write_json(self.pending, 'pending_{}.json'.format(node), intent)
def dispatched_actions(self):
return [json.loads(c.args[0][3][len('pillar='):])['actions'] for c in self.run.call_args_list]
def test_keeps_pending_only(self):
self.ck.targets['G@role:so-sensor'] = ['a']
self.ck.pend('a')
source = self.source([SURICATA])
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
intent = self.kept('a')
self.assertEqual(intent['actions'], [
{'state': 'suricata', 'tgt': 'L@a and ( G@role:so-sensor )', 'tgt_type': 'compound'}])
self.assertEqual(intent['pending'], 'a')
self.assertEqual(intent['paths'], ['audit:suricata.config'])
self.assertFalse(os.path.exists(source))
info = self.logged('info')
self.assertIn('push kept for a until its first highstate completes: suricata tgt=G@role:so-sensor', info)
self.assertNotIn('L@a', info)
self.assertNotIn('skipping', info)
self.assertNotIn('nothing to dispatch', info)
def test_keeps_pending_only_highstate(self):
self.ck.targets['*'] = ['a']
self.ck.pend('a')
self.source([{'highstate': True, 'tgt': '*'}], name='pillar_global.json')
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
self.assertEqual(self.kept('a')['actions'], [{'highstate': True, 'tgt': 'L@a and ( * )', 'tgt_type': 'compound'}])
info = self.logged('info')
self.assertIn('push kept for a until its first highstate completes: highstate tgt=*', info)
self.assertNotIn('L@a', info)
self.assertNotIn('error', info.lower())
def test_keeps_and_dispatches(self):
self.ck.pend('a')
source = self.source([SURICATA])
self.assertEqual(drainer.main(), 0)
self.assertEqual(self.dispatched_actions(), [[{'state': 'suricata', 'tgt': '( G@role:so-sensor )' + NOT_PENDING}]])
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
self.assertFalse(os.path.exists(source))
self.assertIn('push kept for a until its first highstate completes: suricata', self.logged('info'))
def test_keeps_several_pending(self):
self.ck.pend('a', 'b')
self.source([SURICATA])
self.assertEqual(drainer.main(), 0)
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
self.assertEqual(self.kept('b')['actions'], [_kept_copy('b', SURICATA)])
self.assertEqual(self.dispatched_actions(), [[{'state': 'suricata', 'tgt': '( G@role:so-sensor )' + NOT_PENDING}]])
self.run.reset_mock()
self.ck.release('a')
self.age('a')
self.age('b')
self.assertEqual(drainer.main(), 0)
self.assertEqual(self.dispatched_actions(), [[
{'state': 'suricata', 'tgt': '( L@a and ( G@role:so-sensor ) )' + NOT_PENDING, 'tgt_type': 'compound'}]])
self.assertFalse(os.path.exists(self.kept_path('a')))
self.assertTrue(os.path.exists(self.kept_path('b')))
def test_keep_merge(self):
strelka = {'state': 'strelka', 'tgt': 'G@role:so-sensor'}
paths = ['audit:p{}'.format(i) for i in range(30)]
self.assertTrue(drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, paths[:15], self.log))
first_touch = self.kept('a')['first_touch']
with patch.object(drainer.time, 'time', return_value=first_touch + 100):
self.assertTrue(drainer._keep_for_pending(
{'a': [_kept_copy('a', strelka), _kept_copy('a', SURICATA)]}, paths[10:], self.log))
intent = self.kept('a')
self.assertEqual(intent['actions'], [_kept_copy('a', SURICATA), _kept_copy('a', strelka)])
self.assertEqual(intent['first_touch'], first_touch)
self.assertEqual(intent['last_touch'], first_touch + 100)
self.assertEqual(intent['paths'], paths[-drainer.MAX_PATHS:])
self.assertEqual(intent['pending'], 'a')
def test_keep_corrupt_file(self):
self.write_json(self.pending, 'pending_a.json', '{nope')
self.assertTrue(drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log))
self.assertIn('cannot read intent', self.logged('warning'))
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
def test_keep_logs_other_tgt_unchanged(self):
action = dict(SURICATA, tgt='L@b and ( G@role:so-sensor )')
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
self.assertIn('push kept for a until its first highstate completes: suricata tgt=L@b and ( G@role:so-sensor )',
self.logged('info'))
self.assertEqual(self.kept('a')['actions'], [action])
def test_keep_logs_nested_parens_tgt(self):
original = '( G@role:so-sensor or G@role:so-heavynode )'
action = _kept_copy('a', dict(SURICATA, tgt=original))
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
self.assertIn('suricata tgt={}\n'.format(original), self.logged('info') + '\n')
self.assertEqual(self.kept('a')['actions'], [action])
def test_keep_logs_prefix_node_tgt_unchanged(self):
action = dict(SURICATA, tgt='L@ab and ( G@role:so-sensor )')
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
self.assertIn('suricata tgt=L@ab and ( G@role:so-sensor )', self.logged('info'))
def test_keep_logs_unterminated_tgt_unchanged(self):
action = dict(SURICATA, tgt='L@a and ( G@role:so-sensor')
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
self.assertIn('suricata tgt=L@a and ( G@role:so-sensor', self.logged('info'))
def test_keep_write_fails(self):
self.ck.targets['G@role:so-sensor'] = ['a', 'c']
self.ck.pend('a')
source = self.source([SURICATA])
real_open = open
def full_disk(path, *args, **kwargs):
if str(path).endswith('pending_a.json.tmp'):
raise OSError(errno.ENOSPC, 'No space left on device')
return real_open(path, *args, **kwargs)
with patch('builtins.open', side_effect=full_disk):
self.assertEqual(drainer.main(), 1)
self.run.assert_not_called()
self.assertTrue(os.path.exists(source))
self.assertFalse(os.path.exists(self.kept_path('a')))
self.assertIn('cannot keep pushes for a until its first highstate completes', self.logged('error'))
self.assertIn('No space left on device', self.logged('error'))
self.assertEqual(drainer.main(), 0)
self.run.assert_called_once()
self.assertFalse(os.path.exists(source))
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
def test_dispatch_fails_keep_once(self):
self.ck.pend('a')
source = self.source([SURICATA])
self.run.side_effect = subprocess.CalledProcessError(1, 'salt-run', '', 'master down')
self.assertEqual(drainer.main(), 1)
self.assertTrue(os.path.exists(source))
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
self.run.side_effect = None
self.assertEqual(drainer.main(), 0)
self.assertFalse(os.path.exists(source))
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
self.assertEqual(len(self.run.call_args_list), 2)
def test_keep_no_relock(self):
lock_fd = os.open(drainer.LOCK_FILE, os.O_CREAT | os.O_RDWR, 0o644)
self.addCleanup(os.close, lock_fd)
fcntl.flock(lock_fd, fcntl.LOCK_EX)
self.addCleanup(fcntl.flock, lock_fd, fcntl.LOCK_UN)
result = []
worker = threading.Thread(
target=lambda: result.append(drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)),
daemon=True)
worker.start()
worker.join(timeout=5)
self.assertFalse(worker.is_alive())
self.assertEqual(result, [True])
self.assertTrue(os.path.exists(self.kept_path('a')))
def test_kept_not_ready_while_pending(self):
self.ck.pend('a')
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
self.age('a')
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
self.assertTrue(os.path.exists(self.kept_path('a')))
self.assertEqual([c.args for c in self.ck.cache.fetch.call_args_list], [('minions/a', 'data')])
self.assertIn('no ready intents (0 still in debounce window, 1 for nodes still in their first highstate)',
self.logged('debug'))
def test_kept_drains_after_release(self):
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, ['audit:suricata.config'], self.log)
self.age('a')
self.ck.release('a')
self.assertEqual(drainer.main(), 0)
self.assertEqual(self.dispatched_actions(), [[
{'state': 'suricata', 'tgt': '( L@a and ( G@role:so-sensor ) )' + NOT_PENDING, 'tgt_type': 'compound'}]])
self.assertFalse(os.path.exists(self.kept_path('a')))
self.assertEqual(len(os.listdir(self.dispatched)), 1)
def test_kept_waits_for_debounce(self):
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
self.ck.release('a')
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
self.ck.cache.fetch.assert_not_called()
self.assertTrue(os.path.exists(self.kept_path('a')))
def test_kept_master_config_error(self):
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
self.age('a')
self.ck.release('a')
with patch.object(drainer.salt.config, 'master_config', side_effect=OSError('no config')):
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
self.assertTrue(os.path.exists(self.kept_path('a')))
self.assertIn('holding kept pushes', self.logged('warning'))
def test_kept_removed_node(self):
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
os.unlink(os.path.join(self.keys, 'a'))
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
self.assertFalse(os.path.exists(self.kept_path('a')))
self.assertIn('removing kept pushes for a: its key is no longer accepted', self.logged('info'))
def test_kept_no_match_dropped(self):
search = {'state': 'elasticsearch', 'tgt': 'G@role:so-searchnode'}
drainer._keep_for_pending({'a': [_kept_copy('a', search)]}, [], self.log)
self.age('a')
self.ck.release('a')
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
self.assertFalse(os.path.exists(self.kept_path('a')))
self.assertIn('skipping elasticsearch: no minions match tgt=L@a and ( G@role:so-searchnode )', self.logged('info'))
def test_kept_uncached_node_greedy(self):
self.accept('m')
manager = {'state': 'nginx', 'tgt': 'G@role:so-manager'}
source = self.source([manager])
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
self.assertFalse(os.path.exists(source))
self.assertEqual(self.kept('m')['actions'], [_kept_copy('m', manager)])
self.ck.release('m')
self.age('m')
self.log.reset_mock()
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
self.assertFalse(os.path.exists(self.kept_path('m')))
self.assertEqual([c.args[0] % c.args[1:] for c in self.log.info.call_args_list if 'skipping' in c.args[0]],
['skipping nginx: no minions match tgt=L@m and ( G@role:so-manager )'])
self.log.reset_mock()
self.assertEqual(drainer.main(), 0)
self.log.info.assert_not_called()
def test_kept_partial_match_consumed(self):
search = {'state': 'elasticsearch', 'tgt': 'G@role:so-searchnode'}
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA), _kept_copy('a', search)]}, [], self.log)
self.age('a')
self.ck.release('a')
self.assertEqual(drainer.main(), 0)
self.assertEqual(self.dispatched_actions(), [[
{'state': 'suricata', 'tgt': '( L@a and ( G@role:so-sensor ) )' + NOT_PENDING, 'tgt_type': 'compound'}]])
self.assertFalse(os.path.exists(self.kept_path('a')))
def test_kept_cache_error_held(self):
search = {'state': 'elasticsearch', 'tgt': 'G@role:so-searchnode'}
drainer._keep_for_pending({'a': [_kept_copy('a', search)]}, [], self.log)
self.age('a')
self.ck.release('a')
self.ck.fetch_error = OSError('cache read failed')
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
self.assertTrue(os.path.exists(self.kept_path('a')))
self.assertIn('cannot read the cached grains of a', self.logged('warning'))
self.assertNotIn('skipping', self.logged('info'))
def test_no_unlink_written_this_pass(self):
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, ['audit:suricata.config'], self.log)
self.age('a')
first_touch = self.kept('a')['first_touch']
self.ck.release('a')
self.ck.pending.add('a')
self.assertEqual(drainer.main(), 0)
self.run.assert_not_called()
intent = self.kept('a')
self.assertEqual(intent['actions'][0], _kept_copy('a', SURICATA))
self.assertIn('push kept for a', self.logged('info'))
self.assertEqual(intent['first_touch'], first_touch)
self.assertGreater(intent['last_touch'], first_touch)
self.assertEqual(intent['paths'], ['audit:suricata.config'])
def test_bad_id(self):
self.ck.targets['*'] = ['bad\n', 'a/../b', 'c']
self.ck.pending = {'bad\n', 'a/../b'}
self.source([{'highstate': True, 'tgt': '*'}], name='pillar_global.json')
for name, node in (('pending_x.json', '../etc'), ('pending_y.json', 5), ('pending_z.json', 'z\n')):
self.write_json(self.pending, name, {'pending': node, 'last_touch': 0, 'actions': [SURICATA]})
self.assertEqual(drainer.main(), 0)
self.assertEqual(os.listdir(self.pending), ['.lock'])
self.assertEqual(self.dispatched_actions(), [[{'highstate': True, 'tgt': '( * )' + NOT_PENDING}]])
for call in self.run.call_args_list:
self.assertNotIn('bad', call.args[0][3])
self.assertNotIn('a/../b', call.args[0][3])
warning = self.logged('warning')
self.assertIn("not keeping highstate for 'bad\\n': not a valid node id", warning)
self.assertIn("not keeping highstate for 'a/../b'", warning)
self.assertIn("'../etc' is not a valid node id", warning)
self.assertIn('5 is not a valid node id', warning)
self.assertIn("'z\\n' is not a valid node id", warning)
self.assertNotIn('push kept', self.logged('info'))
class TestMain(DrainerTestCase):
@@ -1023,8 +474,7 @@ class TestMain(DrainerTestCase):
('_make_logger', {'return_value': self.log}),
('_load_push_cfg', {'side_effect': lambda: self.cfg}),
('_check_dispatched', {}),
('_targeted', {'side_effect': lambda actions, log: (actions, {})}),
('_master_settling', {'return_value': False}),
('_targeted', {'side_effect': lambda actions, log: actions}),
):
patcher = patch.object(drainer, name, **kwargs)
setattr(self, name, patcher.start())
@@ -1078,16 +528,6 @@ class TestMain(DrainerTestCase):
with patch.object(drainer.os, 'unlink', side_effect=OSError('busy')):
self.assertEqual(drainer.main(), 0)
def test_holds_while_master_settling(self):
path = self.intent('pillar_soc.json')
self._master_settling.return_value = True
with patch.object(drainer, '_dispatch') as dispatch:
self.assertEqual(drainer.main(), 0)
dispatch.assert_not_called()
self._check_dispatched.assert_called_once()
self.assertTrue(os.path.exists(path))
self.assertIn('holding 1 intent(s)', self.logged('info'))
def test_dispatch_failure_keeps_intents(self):
path = self.intent('pillar_soc.json')
with patch.object(drainer, '_dispatch', return_value=None):
@@ -1120,7 +560,7 @@ class TestMain(DrainerTestCase):
def test_untargeted_not_dispatched(self):
path = self.intent('strelka.json', actions=[{'state': 'strelka', 'tgt': 'G@role:so-sensor'}])
self._targeted.side_effect = None
self._targeted.return_value = ([], {})
self._targeted.return_value = []
with patch.object(drainer, '_dispatch') as dispatch, \
patch.object(drainer, '_record_dispatch') as record:
self.assertEqual(drainer.main(), 0)
@@ -1130,15 +570,15 @@ class TestMain(DrainerTestCase):
self.assertIn('no action matches a minion; nothing to dispatch', self.logged('info'))
def test_dispatches_only_targeted(self):
matched = {'state': 'soc', 'tgt': '*'}
self.intent('mixed.json', actions=[matched, {'state': 'strelka', 'tgt': 'G@role:so-sensor'}])
kept = {'state': 'soc', 'tgt': '*'}
self.intent('mixed.json', actions=[kept, {'state': 'strelka', 'tgt': 'G@role:so-sensor'}])
self._targeted.side_effect = None
self._targeted.return_value = ([matched], {})
self._targeted.return_value = [kept]
with patch.object(drainer, '_dispatch', return_value=JID) as dispatch, \
patch.object(drainer, '_record_dispatch') as record:
self.assertEqual(drainer.main(), 0)
self.assertEqual(dispatch.call_args[0][0], [matched])
self.assertEqual(record.call_args[0][1], [matched])
self.assertEqual(dispatch.call_args[0][0], [kept])
self.assertEqual(record.call_args[0][1], [kept])
if __name__ == '__main__':
+10 -7
View File
@@ -39,8 +39,8 @@ SETTLE_STABLE_CHECKS=3
SETTLE_INITIAL_WAIT=${GRID_HIGHSTATE_SETTLE_INITIAL_WAIT:-45}
BATCH=""
BATCH_WAIT=""
SALT_UPGRADED=false
IGNORED_BATCH_WAIT=false
REASON="manual"
log() {
@@ -48,14 +48,14 @@ log() {
}
usage() {
echo "Usage: so-soup-grid-highstate [--batch <spec>] [--salt-upgraded] [--reason <text>]"
echo "Usage: so-soup-grid-highstate [--batch <spec>] [--batch-wait <sec>] [--salt-upgraded] [--reason <text>]"
exit 1
}
while [ $# -gt 0 ]; do
case "$1" in
--batch) BATCH="$2"; shift 2 ;;
--batch-wait) IGNORED_BATCH_WAIT=true; shift 2 ;;
--batch-wait) BATCH_WAIT="$2"; shift 2 ;;
--salt-upgraded) SALT_UPGRADED=true; shift ;;
--reason) REASON="$2"; shift 2 ;;
-h|--help) usage ;;
@@ -64,7 +64,6 @@ while [ $# -gt 0 ]; do
done
mkdir -p "$(dirname "$LOG_FILE")" "$(dirname "$LOCK_FILE")"
[ "$IGNORED_BATCH_WAIT" = "true" ] && log "--batch-wait is no longer supported and is ignored"
# Serialize: a second invocation (e.g. two soups, or a manual run overlapping soup's)
# should not dispatch a competing set of batches.
@@ -80,6 +79,10 @@ if [ -z "$BATCH" ]; then
BATCH=$(salt-call --out=newline_values_only pillar.get salt:auto_apply:batch 2>/dev/null)
[ -z "$BATCH" ] && BATCH='10%'
fi
if [ -z "$BATCH_WAIT" ]; then
BATCH_WAIT=$(salt-call --out=newline_values_only pillar.get salt:auto_apply:batch_wait 2>/dev/null)
[ -z "$BATCH_WAIT" ] && BATCH_WAIT=15
fi
MINIONID=$(salt-call --local --out=newline_values_only grains.get id 2>/dev/null)
[ -z "$MINIONID" ] && MINIONID=$(cat /etc/salt/minion_id 2>/dev/null)
@@ -97,7 +100,7 @@ if [ "$NUM_ACCEPTED" -le 1 ]; then
exit 0
fi
log "starting grid highstate: reason=$REASON minion=$MINIONID accepted=$NUM_ACCEPTED batch=$BATCH salt_upgraded=$SALT_UPGRADED"
log "starting grid highstate: reason=$REASON minion=$MINIONID accepted=$NUM_ACCEPTED batch=$BATCH batch_wait=$BATCH_WAIT salt_upgraded=$SALT_UPGRADED"
# Count minions currently responsive on the bus (includes this manager).
count_up() {
@@ -168,7 +171,7 @@ if [ "$SALT_UPGRADED" = "true" ]; then
PRE_UP=$(count_up); PRE_UP=${PRE_UP:-1}
log "pre-upgrade reachable minions (incl. this manager): $PRE_UP"
dispatch "salt-upgrade pass (all remote minions)" \
"[{\"highstate\": true, \"tgt\": \"not $MINIONID\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\"}]" \
"[{\"highstate\": true, \"tgt\": \"not $MINIONID\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\", \"batch_wait\": $BATCH_WAIT}]" \
true
log "waiting for minions to reconnect on the new salt version"
wait_for_settle "$PRE_UP"
@@ -199,7 +202,7 @@ for tgt in "${TIER_TGTS[@]}"; do
n=$(tier_count "$tgt"); n=${n:-0}
if [ "$n" -ge 1 ]; then
[ -n "$actions" ] && actions="$actions, "
actions="$actions{\"highstate\": true, \"tgt\": \"$tgt\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\"}"
actions="$actions{\"highstate\": true, \"tgt\": \"$tgt\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\", \"batch_wait\": $BATCH_WAIT}"
log "tier matched $n minion(s): $tgt"
else
log "tier matched 0 minions, skipping: $tgt"
+8 -18
View File
@@ -399,16 +399,6 @@ function syncElastic() {
fi
}
function syncInfluxdbUser() {
local op=$1
local email=$2
if ! docker ps -a --format '{{.Names}}' < /dev/null | grep -qx so-influxdb; then
echo "Skipped InfluxDB $op for $email: the so-influxdb container does not exist, so InfluxDB was not changed." >&2
return 0
fi
so-influxdb-manage "$op" "$email"
}
function syncAll() {
ensureRoleFileExists
@@ -604,9 +594,9 @@ case "${operation}" in
createUser "$email" "${role:-$DEFAULT_ROLE}" "${firstName}" "${lastName}" "${note}"
syncAll
echo "Successfully added new user to SOC"
echo "$password" | syncInfluxdbUser useradd "$email"
echo "$password" | so-influxdb-manage useradd "$email"
if [[ "$role" == "superuser" ]]; then
echo "$password" | syncInfluxdbUser userpromote "$email"
echo "$password" | so-influxdb-manage userpromote "$email"
fi
;;
@@ -626,7 +616,7 @@ case "${operation}" in
syncElastic
echo "Successfully added role to user"
if [[ "$role" == "superuser" ]]; then
echo "$password" | syncInfluxdbUser userpromote "$email"
echo "$password" | so-influxdb-manage userpromote "$email"
fi
fi
;;
@@ -642,7 +632,7 @@ case "${operation}" in
syncElastic
echo "Successfully removed role from user"
if [[ "$role" == "superuser" ]]; then
echo "$password" | syncInfluxdbUser userdemote "$email"
echo "$password" | so-influxdb-manage userdemote "$email"
fi
;;
@@ -654,7 +644,7 @@ case "${operation}" in
updateUserPassword "$email"
syncAll
echo "Successfully updated user password"
echo "$password" | syncInfluxdbUser userpass "$email"
echo "$password" | so-influxdb-manage userpass "$email"
;;
"profile")
@@ -674,7 +664,7 @@ case "${operation}" in
updateStatus "$email" 'active'
syncAll
echo "Successfully enabled user"
syncInfluxdbUser userenable "$email"
so-influxdb-manage userenable "$email"
;;
"disable")
@@ -685,7 +675,7 @@ case "${operation}" in
updateStatus "$email" 'locked'
syncAll
echo "Successfully disabled user"
syncInfluxdbUser userdisable "$email"
so-influxdb-manage userdisable "$email"
;;
"delete")
@@ -696,7 +686,7 @@ case "${operation}" in
deleteUser "$email"
syncAll
echo "Successfully deleted user"
syncInfluxdbUser userdel "$email"
so-influxdb-manage userdel "$email"
;;
"sync")
+14 -244
View File
@@ -361,187 +361,6 @@ check_fleet_server() {
fi
}
TELEGRAF_PILLAR=/opt/so/saltstack/local/pillar/telegraf/soc_telegraf.sls
TELEGRAF_CREDS=/opt/so/saltstack/local/pillar/telegraf/creds.sls
INFLUXDB_DIRS=(/nsm/influxdb /opt/so/conf/influxdb)
telegraf_creds_present() {
local mid=$1
[[ -n $(so-yaml.py get -r "$TELEGRAF_CREDS" "telegraf.postgres_creds.${mid}.user" 2>/dev/null) ]] &&
[[ -n $(so-yaml.py get -r "$TELEGRAF_CREDS" "telegraf.postgres_creds.${mid}.pass" 2>/dev/null) ]]
}
# An unreadable docker or directory state counts as present so the POSTGRES path
# asks, or refuses on -y, rather than letting a highstate delete data unannounced.
influxdb_container_exists() {
local names
names=$(docker ps -a --format '{{.Names}}' 2>/dev/null) || return 0
grep -qx so-influxdb <<< "$names"
}
influxdb_present() {
local dir contents
influxdb_container_exists && return 0
for dir in "${INFLUXDB_DIRS[@]}"; do
[[ -e $dir ]] || continue
contents=$(ls -A "$dir" 2>/dev/null) || return 0
[[ -n $contents ]] && return 0
done
return 1
}
set_influxdb_size() {
local dir
local -a existing=()
for dir in "${INFLUXDB_DIRS[@]}"; do
[[ -e $dir ]] && existing+=("$dir")
done
INFLUXDB_SIZE=0
(( ${#existing[@]} == 0 )) && return 0
if ! INFLUXDB_SIZE=$(set -o pipefail; du -sch "${existing[@]}" 2>/dev/null | tail -n 1 | cut -f1) || [[ -z $INFLUXDB_SIZE ]]; then
FINAL_MESSAGE_QUEUE+=("WARNING: Unable to measure the size of InfluxDB's data in ${INFLUXDB_DIRS[*]}.")
INFLUXDB_SIZE="an unknown amount"
fi
}
influxdb_switch_prompt() {
local output answer mid mids
local -a missing=()
# read the pillar files rather than salt, as influxdb_switch_apply must while salt-master is stopped
output=$(so-yaml.py get -r "$TELEGRAF_PILLAR" telegraf.output 2>/dev/null) ||
output=$(so-yaml.py get -r "$DEFAULT_SALT_DIR/salt/telegraf/defaults.yaml" telegraf.output 2>/dev/null) ||
output=INFLUXDB
output=${output^^}
if [[ "$output" == "POSTGRES" ]]; then
if ! telegraf_creds_present "$MINIONID"; then
echo ""
echo "The metrics output is POSTGRES, but this manager has no Telegraf Postgres credentials."
echo "The upgrade cannot complete without them. soup has not changed anything."
echo ""
echo "Add them, then run soup again:"
echo " sudo so-telegraf-cred add $MINIONID"
echo ""
exit 0
fi
influxdb_present || return 0
set_influxdb_size
if [[ -n $UNATTENDED ]]; then
if [[ -n $DELETES_ACCEPTED ]]; then
INFLUX_DELETE_ACCEPTED=1
echo "InfluxDB ($INFLUXDB_SIZE) is still present on this POSTGRES grid; its deletion was accepted with --deletes-accepted."
return 0
fi
echo ""
echo "The metrics output is POSTGRES, so this upgrade would remove InfluxDB and delete"
echo "all of its data ($INFLUXDB_SIZE). The deletion cannot be undone. soup has not changed anything."
echo ""
echo "To continue, choose one of the following:"
echo " - Accept the deletion: sudo soup -y --deletes-accepted"
echo " - Confirm the deletion at the prompt: sudo soup"
echo " - Save the data if needed and remove InfluxDB by hand, then run sudo soup -y again:"
# the installed release's scheduled highstate would otherwise start InfluxDB again before soup runs
echo " sudo so-yaml.py replace /opt/so/saltstack/local/pillar/minions/$MINIONID.sls influxdb.enabled false"
echo " sudo docker rm -f so-influxdb"
echo " sudo find ${INFLUXDB_DIRS[*]} -mindepth 1 -delete"
echo ""
exit 0
fi
echo ""
echo "The metrics output is POSTGRES, but InfluxDB is still on this manager with $INFLUXDB_SIZE"
echo "of old data. This upgrade removes InfluxDB and deletes all of that data, and the"
echo "deletion cannot be undone."
echo "Exit now if you want to save or export the data first, then run soup again."
echo ""
read -rp "Press C to continue with the upgrade or E to exit: " answer
if [[ "$answer" != [cC] ]]; then
echo "Exiting soup"
exit 0
fi
return 0
fi
# releases before 3.1.0 have no Telegraf credentials; influxdb_switch_apply creates them on a switch
[[ $INSTALLEDVERSION =~ ^(2\.|3\.0\.) ]] && INFLUX_CREATE_CREDS=1
if ! mids=$(salt-key --out=json --list=accepted 2>/dev/null | jq -r '.minions[]?' 2>/dev/null) || [[ -z $mids ]]; then
missing=("(unable to list accepted minions)")
else
INFLUX_SWITCH_MINIONS=$mids
if [[ -z $INFLUX_CREATE_CREDS ]]; then
for mid in $mids; do
telegraf_creds_present "$mid" || missing+=("$mid")
done
fi
fi
if (( ${#missing[@]} > 0 )); then
FINAL_MESSAGE_QUEUE+=("NOTE: soup did not offer to move metrics from InfluxDB to Postgres because these nodes have no Telegraf Postgres credentials: ${missing[*]}")
FINAL_MESSAGE_QUEUE+=(" - Add them with sudo so-telegraf-cred add <minion_id>; the next soup will offer the switch.")
return 0
fi
if [[ -n $UNATTENDED ]]; then
FINAL_MESSAGE_QUEUE+=("NOTE: InfluxDB will be removed in a future Security Onion release, and this grid still stores metrics in it (telegraf.output is $output).")
FINAL_MESSAGE_QUEUE+=(" - Setting telegraf.output to POSTGRES in Configuration switches the grid to Postgres and deletes InfluxDB and all its data.")
return 0
fi
echo ""
echo "InfluxDB will be removed in a future Security Onion release. This grid stores its"
echo "metrics in InfluxDB (telegraf.output is $output)."
echo ""
echo "Every grid must move its metrics to Postgres before that release. Existing InfluxDB"
echo "metrics are not migrated."
echo ""
echo "Switching now points Telegraf at Postgres and removes InfluxDB, deleting all of its"
echo "data, during this upgrade. This cannot be undone, and switching back afterwards is"
echo "not supported. InfluxDB's alarm checks are deleted with it; the Postgres recommended"
echo "alarms can be added from the Grid page."
echo ""
read -rp "Switch metrics to Postgres now? [y/N]: " answer
if [[ "$answer" == [yY] ]]; then
INFLUX_SWITCH_ACCEPTED=1
else
echo "Keeping telegraf.output set to $output."
fi
}
influxdb_switch_apply() {
local mid
local -a failed=()
[[ -n $INFLUX_SWITCH_ACCEPTED ]] || return 0
if [[ -n $INFLUX_CREATE_CREDS ]]; then
echo "Creating Telegraf Postgres credentials for accepted minions."
for mid in $INFLUX_SWITCH_MINIONS; do
bash "$UPDATE_DIR/salt/manager/tools/sbin/so-telegraf-cred" add "$mid" || failed+=("$mid")
done
if (( ${#failed[@]} > 0 )); then
FINAL_MESSAGE_QUEUE+=("WARNING: Unable to create Telegraf Postgres credentials for these nodes, so the grid stays on its current metrics output: ${failed[*]}")
FINAL_MESSAGE_QUEUE+=(" - Once their credentials exist, set telegraf.output to POSTGRES in Configuration to switch.")
return 0
fi
fi
echo "Setting telegraf.output to POSTGRES in $TELEGRAF_PILLAR."
if ! { mkdir -p "$(dirname "$TELEGRAF_PILLAR")" && touch "$TELEGRAF_PILLAR" &&
so-yaml.py replace "$TELEGRAF_PILLAR" telegraf.output POSTGRES; }; then
FINAL_MESSAGE_QUEUE+=("WARNING: Unable to set telegraf.output to POSTGRES in $TELEGRAF_PILLAR, so metrics stay in InfluxDB. Set it in Configuration to switch.")
return 0
fi
chown socore:socore "$TELEGRAF_PILLAR" 2>/dev/null || true
}
influxdb_retire_check() {
[[ "$(so_telegraf_output 2>/dev/null)" == "POSTGRES" ]] || return 0
if influxdb_container_exists; then
FINAL_MESSAGE_QUEUE+=("NOTE: InfluxDB is still on this manager. The next highstate tries again to remove it and delete all its data.")
elif [[ -n $INFLUX_DELETE_ACCEPTED ]]; then
FINAL_MESSAGE_QUEUE+=("NOTE: This upgrade removed InfluxDB and deleted all its data, as accepted with --deletes-accepted.")
fi
}
check_saltmaster_status() {
set +e
echo "Waiting on the Salt Master service to be ready."
@@ -1289,6 +1108,9 @@ post_to_3.3.0() {
### 3.4.0 Scripts ###
up_to_3.4.0() {
# download 9.4.8 elastic agent packages
determine_elastic_agent_upgrade
set_soauth_range
echo "Removing so-kratos, so-hydra and so-soc so they are recreated on the soauth network."
@@ -1366,6 +1188,10 @@ valid_soauth_range() {
}
post_to_3.4.0() {
# Generate 9.4.8 elastic agent installers
echo "Regenerating Elastic Agent Installers"
/sbin/so-elastic-agent-gen-installers
for idx in "metrics-logstash.node-default" "metrics-logstash.stack_monitoring.node-default"; do
rollover_index "$idx"
done
@@ -1395,11 +1221,7 @@ add_detection_runtime_fields() {
### 3.5.0 Scripts ###
up_to_3.5.0() {
# download 9.4.10 elastic agent packages
determine_elastic_agent_upgrade
remove_localrules_portgroup
remove_auto_apply_batch_wait
INSTALLEDVERSION=3.5.0
}
@@ -1416,42 +1238,8 @@ remove_localrules_portgroup() {
done
}
remove_auto_apply_batch_wait() {
local pillar_file
for pillar_file in /opt/so/saltstack/local/pillar/salt/{soc,adv}_salt.sls; do
grep -qs batch_wait "$pillar_file" || continue
so-yaml.py get -r "$pillar_file" salt.auto_apply.batch_wait >/dev/null 2>&1 || continue
echo "Removing salt.auto_apply.batch_wait from $pillar_file."
if ! so-yaml.py remove "$pillar_file" salt.auto_apply.batch_wait; then
FINAL_MESSAGE_QUEUE+=("WARNING: Unable to remove the unused salt.auto_apply.batch_wait setting from $pillar_file. It has no effect and can be removed manually:")
FINAL_MESSAGE_QUEUE+=(" - sudo so-yaml.py remove $pillar_file salt.auto_apply.batch_wait")
fi
done
}
check_soc_postgres_upgrade() {
local image
[[ "$(so_telegraf_output 2>/dev/null)" != "INFLUXDB" ]] || return 0
telegraf_creds_present "$MINIONID" || return 0
image=$(docker inspect --format '{{.Config.Image}}' so-soc 2>/dev/null) || image=
if [[ "$image" != *":$NEWVERSION" ]]; then
echo ""
echo "WARNING: SOC was not upgraded to $NEWVERSION because the Telegraf Postgres role setup failed. Fix Postgres, then run a highstate:"
echo " - sudo salt-call state.highstate"
fi
}
post_to_3.5.0() {
# Generate 9.4.10 elastic agent installers
echo "Regenerating Elastic Agent Installers"
/sbin/so-elastic-agent-gen-installers
telegraf_repair
# ensure manager has new version of socloud.conf
if [[ $SALT_CLOUD_CONFIGURED == true ]]; then
salt-call state.apply salt.cloud.config concurrent=True || FINAL_MESSAGE_QUEUE+=("WARNING: Unable to update the salt-cloud profile. Run: sudo salt-call state.apply salt.cloud.config")
fi
rollover_index "logs-detections.alerts-so"
@@ -1731,11 +1519,10 @@ verify_es_version_compatibility() {
["8.18.4"]="8.18.6 8.18.8 9.0.8"
["8.18.6"]="8.18.8 9.0.8"
["8.18.8"]="9.0.8"
["9.0.8"]="9.3.3 9.3.7 9.4.5 9.4.8 9.4.10"
["9.3.3"]="9.3.7 9.4.5 9.4.8 9.4.10"
["9.3.7"]="9.4.5 9.4.8 9.4.10"
["9.4.5"]="9.4.8 9.4.10"
["9.4.8"]="9.4.10"
["9.0.8"]="9.3.3 9.3.7 9.4.5 9.4.8"
["9.3.3"]="9.3.7 9.4.5 9.4.8"
["9.3.7"]="9.4.5 9.4.8"
["9.4.5"]="9.4.8"
)
# Elasticsearch MUST upgrade through these versions
@@ -2357,10 +2144,6 @@ main() {
check_cluster_health
check_fleet_server
if [[ "$is_hotfix" != "true" ]]; then
influxdb_switch_prompt
fi
echo "Checking for Salt Master and Minion updates."
upgrade_check_salt
set -e
@@ -2450,7 +2233,6 @@ main() {
echo "Running so-config-backup script."
/sbin/so-config-backup
fi
influxdb_switch_apply
echo ""
echo "Copying new Security Onion code from $UPDATE_DIR to $DEFAULT_SALT_DIR."
@@ -2528,7 +2310,7 @@ main() {
fi
set -e
highstate || { rc=$?; check_soc_postgres_upgrade; exit $rc; }
highstate
check_saltmaster_status
postupgrade_changes
[[ $is_airgap -eq 0 ]] && unmount_update
@@ -2602,8 +2384,6 @@ For more information, please see $DOC_BASE_URL/soup#distributed-deployments.
EOF
fi
influxdb_retire_check
fi
if [ "$NOTIFYCUSTOMELASTICCONFIG" = true ] ; then
@@ -2631,22 +2411,12 @@ fi
echo "### soup has been served at $(date) ###"
}
soup_args=()
for arg in "$@"; do
if [[ "$arg" == "--deletes-accepted" ]]; then
DELETES_ACCEPTED=true
else
soup_args+=("$arg")
fi
done
set -- "${soup_args[@]}"
while getopts ":b:f:y" opt; do
case ${opt} in
b )
BATCHSIZE="$OPTARG"
# Accept either a plain count (e.g. 5) or a percentage (e.g. 25%); passed through
# to so-soup-grid-highstate --batch, which salt's batch accepts in both forms.
# to so-soup-grid-highstate --batch, which salt's batch/batch_wait accepts in both forms.
if ! [[ "$BATCHSIZE" =~ ^[1-9][0-9]*%?$ ]]; then
echo "Batch size must be a number greater than 0, optionally with a trailing % (e.g. 5 or 25%)."
exit 1
@@ -2664,7 +2434,7 @@ while getopts ":b:f:y" opt; do
ISOLOC="$OPTARG"
;;
\? )
echo "Usage: soup [-b] [-y] [--deletes-accepted] [-f <iso location>]"
echo "Usage: soup [-b] [-y] [-f <iso location>]"
exit 1
;;
: )
+2 -3
View File
@@ -1,8 +1,9 @@
{%- from 'vars/globals.map.jinja' import GLOBALS %}
{%- from 'docker/docker.map.jinja' import DOCKERMERGED %}
{%- from 'nginx/map.jinja' import NGINXMERGED %}
{%- from 'telegraf/map.jinja' import INFLUX_RETIRED %}
{%- set role = grains.id.split('_') | last %}
{%- set influxpass = salt['pillar.get']('secrets:influx_pass') %}
{%- set influxauth = ('so:' + influxpass) | base64_encode %}
{%- set all_names = [GLOBALS.hostname, GLOBALS.url_base] + NGINXMERGED.ssl.alt_names %}
{%- set full_server_name = all_names | unique | join(' ') %}
@@ -309,7 +310,6 @@ http {
autoindex_localtime on;
}
{%- if not INFLUX_RETIRED %}
location /influxdb/ {
auth_request /auth/sessions/whoami;
rewrite /influxdb/api/(.*) /api/$1 break;
@@ -323,7 +323,6 @@ http {
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cookie_path /api/ /influxdb/api/;
}
{%- endif %}
location /app/dashboards/ {
auth_request /auth/sessions/whoami;
+3 -27
View File
@@ -1,50 +1,26 @@
{% from 'salt/auto_apply.map.jinja' import AUTOAPPLY %}
{% set actions = salt['pillar.get']('actions', []) %}
{% set BATCH = AUTOAPPLY.batch %}
{# Must exceed gather_job_timeout (10s): at the 5s default, one saltutil.find_job reply slower than that abandons
a queued state run, and a master slow to accept the publish gets it a second time. #}
{% set STATE_TIMEOUT = 60 %}
{% set BATCH_WAIT = AUTOAPPLY.batch_wait %}
{# queue must be a top-level salt.state arg (kwarg is ignored); an int is max_queue and still fails on conflict #}
{# The first step of each action checks that its target is reachable: minions take up to ~22s to rejoin a
restarted master's publisher, and each failed attempt takes ~15s to time out. salt.function does not count
non-responders as failures, so the check passes as soon as any one minion answers. The drainer's 45s hold
covers a restart before dispatch; the retry covers a restart during a running orchestration. expect_minions
is not set on purpose: one offline node would then block the push to every node.
A highstate checks with test.ping: it renders pillar itself, and the global and salt pillar actions push a
highstate to '*', where an unbatched refresh_pillar would make every minion render pillar at once. A single
state needs fresh pillar, so it checks with refresh_pillar. #}
{% for action in actions %}
{% if action.get('highstate') %}
ping_{{ loop.index }}:
salt.function:
- name: test.ping
- tgt: '{{ action.tgt }}'
- tgt_type: {{ action.get('tgt_type', 'compound') }}
- retry:
attempts: 3
interval: 10
apply_highstate_{{ loop.index }}:
salt.state:
- tgt: '{{ action.tgt }}'
- tgt_type: {{ action.get('tgt_type', 'compound') }}
- highstate: True
- batch: {{ action.get('batch', BATCH) }}
- batch_wait: {{ action.get('batch_wait', BATCH_WAIT) }}
- queue: True
- timeout: {{ STATE_TIMEOUT }}
- require:
- salt: ping_{{ loop.index }}
{% else %}
refresh_pillar_{{ loop.index }}:
salt.function:
- name: saltutil.refresh_pillar
- tgt: '{{ action.tgt }}'
- tgt_type: {{ action.get('tgt_type', 'compound') }}
- retry:
attempts: 3
interval: 10
apply_{{ action.state | replace('.', '_') }}_{{ loop.index }}:
salt.state:
@@ -53,8 +29,8 @@ apply_{{ action.state | replace('.', '_') }}_{{ loop.index }}:
- sls:
- {{ action.state }}
- batch: {{ action.get('batch', BATCH) }}
- batch_wait: {{ action.get('batch_wait', BATCH_WAIT) }}
- queue: True
- timeout: {{ STATE_TIMEOUT }}
- require:
- salt: refresh_pillar_{{ loop.index }}
{% endif %}
+6
View File
@@ -6,12 +6,16 @@
{% from 'allowed_states.map.jinja' import allowed_states %}
{% if sls.split('.')[0] in allowed_states %}
{% from 'vars/globals.map.jinja' import GLOBALS %}
{% from 'telegraf/map.jinja' import TELEGRAFMERGED %}
{# postgres.enabled declares the so-postgres container and postgres_wait_ready
that the requires below reference. Salt de-duplicates the circular include. #}
include:
- postgres.enabled
{% set TG_OUT = TELEGRAFMERGED.output | upper %}
{% if TG_OUT in ['POSTGRES', 'BOTH'] %}
# Ensure the shared Telegraf database exists. init-db.sh only runs on a
# fresh data dir, so hosts upgraded onto an existing /nsm/postgres volume
# would otherwise never get so_telegraf.
@@ -66,6 +70,8 @@ postgres_telegraf_retention_reconcile:
- cmd: postgres_telegraf_group_role
- file: postgres_sbin
{% endif %}
{% else %}
{{sls}}_state_not_allowed:
+3 -14
View File
@@ -3,8 +3,7 @@
#
# One pillar directory can map to multiple (state, tgt) actions.
# tgt is a raw salt compound expression. tgt_type is always "compound".
# so-push-drainer keeps pushes for nodes still in their first highstate and applies them after it completes.
# Per-action `batch` overrides the orch default (10%).
# Per-action `batch` / `batch_wait` override the orch defaults (10% / 15s).
# An action with `highstate: True` triggers state.highstate instead of
# state.apply -- see salt/orch/push_batch.sls.
#
@@ -99,7 +98,7 @@ elasticfleet:
# global: fanout to a fleetwide highstate. The global pillar (soc_global.sls)
# carries cross-cutting settings (pipeline, url_base, imagerepo, mdengine, ...)
# that are consumed by virtually every state, so a targeted re-apply isn't
# meaningful. The drainer's batch throttling controls blast radius.
# meaningful. The drainer's batch/batch_wait throttling controls blast radius.
global:
- highstate: True
tgt: '*'
@@ -232,20 +231,10 @@ suricata:
- state: suricata
tgt: 'G@role:so-eval or G@role:so-heavynode or G@role:so-import or G@role:so-sensor or G@role:so-standalone'
# telegraf: universal, then the manager states that follow the output setting.
# They run after telegraf so InfluxDB is retired and SOC switches metrics
# modules only once the nodes already point at the new output.
# telegraf: universal.
telegraf:
- state: telegraf
tgt: '*'
- state: influxdb
tgt: 'G@role:so-eval or G@role:so-import or G@role:so-manager or G@role:so-managerhype or G@role:so-managersearch or G@role:so-standalone'
- state: nginx
tgt: 'G@role:so-eval or G@role:so-import or G@role:so-manager or G@role:so-managerhype or G@role:so-managersearch or G@role:so-standalone'
- state: firewall
tgt: 'G@role:so-eval or G@role:so-import or G@role:so-manager or G@role:so-managerhype or G@role:so-managersearch or G@role:so-standalone'
- state: soc
tgt: 'G@role:so-eval or G@role:so-import or G@role:so-manager or G@role:so-managerhype or G@role:so-managersearch or G@role:so-standalone'
# versionlock: universal (top-of-file '*' branch in salt/top.sls).
versionlock:
+1 -1
View File
@@ -117,7 +117,7 @@ def _app_from_setting(setting_id):
def _node_actions(entry, node_id):
# Copy the app's mapped actions but narrow each one to the single node.
# Preserves the state/highstate selection and any batch override.
# Preserves the state/highstate selection and any batch/batch_wait overrides.
# The app's own target is kept so the state is not applied to a node that does not
# run the app (e.g. an elasticsearch setting saved for a sensor fails to render there).
actions = []
+3 -1
View File
@@ -19,6 +19,8 @@ so-redis:
docker_container.running:
- image: {{ GLOBALS.registry_host }}:5000/{{ GLOBALS.image_repo }}/so-redis:{{ GLOBALS.so_version }}
- restart_policy: unless-stopped
- shutdown_timeout: 180
- stop_timeout: 180
- hostname: so-redis
- user: socore
- networks:
@@ -60,7 +62,7 @@ so-redis:
- {{ ULIMIT.name }}={{ ULIMIT.soft }}:{{ ULIMIT.hard }}
{% endfor %}
{% endif %}
- entrypoint: "redis-server /usr/local/etc/redis/redis.conf"
- entrypoint: "redis-server /usr/local/etc/redis/redis.conf --rdb-version-check relaxed"
- watch:
- cmd: ca_trust_extract
- file: trusttheca
@@ -28,8 +28,6 @@ sool9_{{host}}:
grains:
hypervisor_host: {{host ~ "_" ~ role}}
sosmodel: HVGUEST
# so-push-drainer leaves the VM alone until its first highstate removes this
first_highstate_pending: True
preflight_cmds:
- |
{%- set hostnames = [MANAGERHOSTNAME] %}
+1
View File
@@ -4,5 +4,6 @@ salt:
debounce_seconds: 30
drain_interval: 15
batch: '10%'
batch_wait: 15
schedule:
highstate_interval_minutes: 120
-9
View File
@@ -2,12 +2,3 @@ lasthighstate:
file.touch:
- name: /opt/so/log/salt/lasthighstate
- order: 9001
# Set by setup and the hypervisor VM cloud profile; so-push-drainer does not target a node that still has it.
# Auto-ordered states start at 10000, and a negative order runs after all of them, just before the
# order: last states, so the grain goes only once the highstate has run every state. The touch above stays
# at 9001 because so-status and so-salt-minion-check read it.
first_highstate_pending:
grains.absent:
- destructive: True
- order: -1
+11 -5
View File
@@ -3,32 +3,38 @@ salt:
enabled:
description: Master kill-switch for the active push feature. When disabled, rule and pillar changes are picked up at the next scheduled highstate instead of being pushed immediately.
forcedType: bool
helpLink: salt
helpLink: push
global: True
debounce_seconds:
description: Trailing-edge debounce window in seconds. A push intent must be quiet for this long before the drainer dispatches. Rapid bursts of edits within this window coalesce into one dispatch.
forcedType: int
helpLink: salt
helpLink: push
global: True
advanced: True
drain_interval:
description: How often the push drainer checks for ready intents, in seconds. Small values lower dispatch latency at the cost of more background work on the manager.
forcedType: int
helpLink: salt
helpLink: push
global: True
advanced: True
batch:
description: "Host batch size for push orchestrations. A number (e.g. '10') or a percentage (e.g. '25%'). Limits how many minions run the push state at once so large fleets don't thundering-herd."
helpLink: salt
helpLink: push
global: True
advanced: True
regex: '^([0-9]+%?)$'
regexFailureMessage: Enter a whole number or a whole-number percentage (e.g. 10 or 25%).
batch_wait:
description: Seconds to wait between host batches in a push orchestration. Gives the fleet time to breathe between waves.
forcedType: int
helpLink: push
global: True
advanced: True
schedule:
highstate_interval_minutes:
description: How often every minion in the grid runs a scheduled state.highstate, in minutes. Minimum 15 minutes. Lower values keep minions closer in sync at the cost of more load; higher values reduce load but increase worst-case latency for non-pushed changes. If Auto Apply is disabled, set this to the 15-minute minimum so changes are still picked up promptly. The salt-minion health check restarts a minion if its last state apply is older than this value plus one hour.
forcedType: int
helpLink: salt
helpLink: push
global: True
advanced: True
regex: '^(1[5-9]|[2-9][0-9]|[1-9][0-9]{2,4})$'
-9
View File
@@ -5,14 +5,9 @@
{% from 'allowed_states.map.jinja' import allowed_states %}
{% if sls.split('.')[0] in allowed_states %}
{% from 'soc/merged.map.jinja' import SOCMERGED %}
{% set use_pg_metrics = 'postgresmetrics' in SOCMERGED.config.server.modules %}
include:
- manager.sync_es_users
{% if use_pg_metrics %}
- postgres.telegraf_users
{% endif %}
sigmarepodir:
file.directory:
@@ -82,10 +77,6 @@ socconfig:
- mode: 600
- template: jinja
- show_changes: False
{% if use_pg_metrics %}
- require:
- sls: postgres.telegraf_users
{% endif %}
socmotd:
file.managed:
-55
View File
@@ -2557,61 +2557,6 @@ soc:
grid:
maxUploadSize: 26214400
staleMetricsMs: 120000
recommendedAlarms:
- name: Root Disk Usage
metric: disk
metricKey: disk_used_root
operator: gt
threshold: '95'
durationSeconds: 300
severity: critical
clearedSeverity: info
enabled: true
- name: NSM Disk Usage
metric: disk
metricKey: disk_used_nsm
operator: gt
threshold: '95'
durationSeconds: 300
severity: critical
clearedSeverity: info
enabled: true
- name: Low PCAP Retention
metric: pcap_retention
metricKey: pcap_retention
operator: lt
threshold: '1'
durationSeconds: 300
severity: critical
clearedSeverity: info
enabled: true
- name: Suricata Packet Loss
metric: loss
metricKey: suricata_loss
operator: gt
threshold: '5'
durationSeconds: 300
severity: critical
clearedSeverity: info
enabled: true
- name: Zeek Packet Loss
metric: loss
metricKey: zeek_loss
operator: gt
threshold: '5'
durationSeconds: 300
severity: critical
clearedSeverity: info
enabled: true
- name: Low Monitor Traffic
metric: net
metricKey: traffic_mon_in
operator: lt
threshold: '5'
durationSeconds: 300
severity: critical
clearedSeverity: info
enabled: true
cases:
advanced: false
aggregationActionsEnabled: false
+2 -2
View File
@@ -7,7 +7,7 @@
{% from 'soc/defaults.map.jinja' import SOCDEFAULTS with context %}
{% from 'elasticsearch/config.map.jinja' import ELASTICSEARCH_NODES %}
{% from 'manager/map.jinja' import MANAGERMERGED %}
{% from 'telegraf/map.jinja' import PG_METRICS_READY %}
{% from 'telegraf/map.jinja' import TELEGRAFMERGED %}
{% from 'elastalert/map.jinja' import ELASTALERTMERGED %}
{%- set PG_ENTRY = salt['pillar.get']('telegraf:postgres_creds:' ~ grains.id, {}) %}
{%- set PG_USER = PG_ENTRY.get('user', '') %}
@@ -129,7 +129,7 @@
{% endif %}
{# Define the postgresmetrics module if telegraf is setup to only use Postgres #}
{% if PG_METRICS_READY %}
{% if TELEGRAFMERGED.output != 'INFLUXDB' and PG_USER and PG_PASS %}
{% do SOCMERGED.config.server.modules.update({
'postgresmetrics': {
'database': 'so_telegraf',
-63
View File
@@ -1343,69 +1343,6 @@ soc:
staleMetricsMs:
description: The age in milliseconds of node metrics when they are considered stale. Stale metrics have a faded appearance on the Grid screen.
global: True
recommendedAlarms:
description: Recommended alarms offered on the Grid page's Alarms tab and Options dialog.
global: True
advanced: True
forcedType: "[]{}"
syntax: json
helpLink: grid
uiElements:
- field: name
label: Name
required: True
- field: metric
label: Metric
required: True
- field: metricKey
label: Metric Key
required: False
- field: operator
label: Operator
required: True
options:
- gt
- gte
- lt
- lte
- eq
- ne
- contains
- field: threshold
label: Threshold
required: True
forcedType: string
- field: durationSeconds
label: Duration Seconds
required: False
forcedType: int
- field: severity
label: Severity
required: True
options:
- critical
- high
- medium
- low
- info
- field: clearedSeverity
label: Cleared Severity
required: False
options:
- none
- critical
- high
- medium
- low
- info
- field: enabled
label: Enabled
required: False
forcedType: bool
- field: note
label: Note
required: False
multiline: True
case:
analyzerNodeId:
description: The node ID on which analyzers will be executed.
-19
View File
@@ -158,21 +158,6 @@ tgraf_sbin_jinja:
- defaults:
CONTAINER_STATS: {{ TELEGRAFMERGED.container_stats }}
{% set tg_output = TELEGRAFMERGED.output | upper %}
{% set pg_creds = salt['pillar.get']('telegraf:postgres_creds:' ~ GLOBALS.minion_id, {}) %}
{% set pg_creds_missing = tg_output in ['POSTGRES', 'BOTH'] and not (pg_creds.get('user') and pg_creds.get('pass')) %}
{% if pg_creds_missing %}
{% set pg_creds_text = 'Telegraf Postgres credentials for ' ~ GLOBALS.minion_id ~ ' are missing from the pillar. On the manager, run so-telegraf-cred add ' ~ GLOBALS.minion_id ~ ', then run a highstate on this node.' %}
telegraf_postgres_creds_missing:
{% if tg_output == 'POSTGRES' %}
test.fail_without_changes:
- comment: {{ pg_creds_text | tojson }}
{% else %}
test.show_notification:
- text: {{ pg_creds_text | tojson }}
{% endif %}
{% endif %}
tgrafconf:
file.managed:
- name: /opt/so/conf/telegraf/etc/telegraf.conf
@@ -186,10 +171,6 @@ tgrafconf:
GLOBALS: {{ GLOBALS }}
TELEGRAFMERGED: {{ TELEGRAFMERGED }}
LOGSTASH_MERGED: {{ LOGSTASH_MERGED }}
{% if pg_creds_missing %}
- require:
- test: telegraf_postgres_creds_missing
{% endif %}
# this file will be read by telegraf to send node details (management interface, monitor interface, etc)
# into influx
-14
View File
@@ -6,13 +6,6 @@
{% from 'vars/globals.map.jinja' import GLOBALS %}
{% import_yaml 'telegraf/defaults.yaml' as TELEGRAFDEFAULTS %}
{% set TELEGRAFMERGED = salt['pillar.get']('telegraf', TELEGRAFDEFAULTS.telegraf, merge=True) %}
{% set TG_OUTPUT = TELEGRAFMERGED.output | upper %}
{% set TG_PG_ENTRY = salt['pillar.get']('telegraf:postgres_creds:' ~ GLOBALS.minion_id, {}) %}
{% set PG_METRICS_READY = false %}
{% if TG_OUTPUT != 'INFLUXDB' and TG_PG_ENTRY.get('user') and TG_PG_ENTRY.get('pass') %}
{% set PG_METRICS_READY = true %}
{% endif %}
{% set INFLUX_RETIRED = TG_OUTPUT == 'POSTGRES' and PG_METRICS_READY %}
{% if GLOBALS.role in ['so-eval', 'so-standalone', 'so-sensor', 'so-heavynode'] %}
{% from 'zeek/config.map.jinja' import ZEEKMERGED %}
@@ -29,10 +22,3 @@
{% do TELEGRAFMERGED.scripts[GLOBALS.role.split('-')[1]].remove('redis.sh') %}
{% endif %}
{% endif %}
{% if INFLUX_RETIRED %}
{% set role_scripts = TELEGRAFMERGED.scripts.get(GLOBALS.role.split('-')[1], []) %}
{% if 'influxdbsize.sh' in role_scripts %}
{% do role_scripts.remove('influxdbsize.sh') %}
{% endif %}
{% endif %}
+3 -3
View File
@@ -9,9 +9,9 @@ export REDISCLI_AUTH={{ REDIS_PASS }}
# if this script isn't already running
if [[ ! "`pidof -x $(basename $0) -o %PPID`" ]]; then
UNPARSED=$(redis-cli llen logstash:unparsed | awk '{print $1}')
PARSED=$(redis-cli llen logstash:parsed | awk '{print $1}')
MEM_USED=$(redis-cli info memory | grep used_memory_peak_perc | cut -d ":" -f2 | sed "s/%//")
UNPARSED=$(valkey-cli llen logstash:unparsed | awk '{print $1}')
PARSED=$(valkey-cli llen logstash:parsed | awk '{print $1}')
MEM_USED=$(valkey-cli info memory | grep used_memory_peak_perc | cut -d ":" -f2 | sed "s/%//")
echo "redisqueue unparsed=$UNPARSED,parsed=$PARSED,mem_used=$MEM_USED"
+2 -2
View File
@@ -5,14 +5,14 @@ telegraf:
advanced: True
helpLink: influxdb
output:
description: Selects the backend(s) Telegraf writes metrics to. INFLUXDB keeps the current behavior; POSTGRES writes to the grid's Postgres instance; BOTH dual-writes for migration validation. When set to BOTH, the grid screen's metrics are pulled from Postgres, and the InfluxDB tool link remains visible. When set to POSTGRES, the InfluxDB tool link is removed. WARNING - Choosing POSTGRES removes InfluxDB from the manager and permanently deletes all of its data; this cannot be undone. Switching back to INFLUXDB or BOTH afterwards is not supported, because InfluxDB would start again with no data. BOTH keeps InfluxDB running. InfluxDB will be removed in a future release, so grids should move to POSTGRES.
description: Selects the backend(s) Telegraf writes metrics to. INFLUXDB keeps the current behavior; POSTGRES writes to the grid's Postgres instance; BOTH dual-writes for migration validation. When set to BOTH, the grid screen's metrics are pulled from Postgres, and the InfluxDB tool link remains visible. When set to POSTGRES, the InfluxDB tool link is removed.
options:
- INFLUXDB
- POSTGRES
- BOTH
global: True
advanced: True
helpLink: postgresql
helpLink: influxdb
config:
interval:
description: Data collection interval.
-2
View File
@@ -519,8 +519,6 @@ configure_minion() {
info "Configuring minion type as $minion_type"
logCmd "mkdir -p /etc/salt/minion.d"
echo "role: so-$minion_type" > /etc/salt/grains
# so-push-drainer leaves the node alone until salt.lasthighstate removes this
echo "first_highstate_pending: True" >> /etc/salt/grains
local minion_config=/etc/salt/minion