diff --git a/salt/manager/tools/sbin/so-push-drainer b/salt/manager/tools/sbin/so-push-drainer index 569f47ef2..6f19eea22 100644 --- a/salt/manager/tools/sbin/so-push-drainer +++ b/salt/manager/tools/sbin/so-push-drainer @@ -16,7 +16,11 @@ 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_.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 @@ -46,11 +50,25 @@ 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 @@ -60,6 +78,8 @@ 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})') @@ -117,27 +137,134 @@ def _dedupe_actions(actions): return deduped -def _targeted(actions, log): - """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'.""" +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: - ckminions = salt.utils.minions.CkMinions(salt.config.master_config(MASTER_CONFIG)) + 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.""" + try: + ckminions = _ckminions() except Exception: log.exception('cannot load master config; dispatching without checking targets') - return actions + return [_skip_pending(action) for action in actions], {} + pending = _pending_minions(ckminions, log) 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(action['tgt'], action.get('tgt_type', 'compound')).get('minions') + 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') except Exception: - log.exception('cannot resolve tgt=%s; dispatching it anyway', action.get('tgt')) - matched = True + 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 if matched: - 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 + 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_.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 def _dispatch(actions, log): @@ -221,6 +348,10 @@ 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', ''))) @@ -283,11 +414,21 @@ 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) - # 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) or + # stopped waiting 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) for step in steps) + return bool(steps) and all( + str(step.get('comment', '')).startswith(STEP_RAISED) or _lost_track(step) for step in steps) def _recheck_delay(age): @@ -387,18 +528,39 @@ 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) @@ -406,8 +568,13 @@ def main(): pass if not ready: - if skipped: - log.debug('no ready intents (%d still in debounce window)', skipped) + 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)) return 0 combined_actions = [] @@ -435,24 +602,32 @@ 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[:20], + debounce_duration, all_paths[:MAX_PATHS], ) for action in deduped: log.info('action: %s tgt=%s', 'highstate' if action.get('highstate') else action.get('state'), action.get('tgt')) - targeted = _targeted(deduped, log) + 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} + 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[:20], log) - else: + _record_dispatch(jid, targeted, all_paths[:MAX_PATHS], log) + elif not kept: 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: diff --git a/salt/manager/tools/sbin/so-push-drainer_test.py b/salt/manager/tools/sbin/so-push-drainer_test.py index a6deab5f2..990924563 100644 --- a/salt/manager/tools/sbin/so-push-drainer_test.py +++ b/salt/manager/tools/sbin/so-push-drainer_test.py @@ -3,14 +3,18 @@ # 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 @@ -34,6 +38,8 @@ 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') @@ -88,6 +94,22 @@ 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, @@ -199,6 +221,17 @@ 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): @@ -265,6 +298,13 @@ 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) @@ -308,7 +348,17 @@ class TestResults(DrainerTestCase): def test_result_unknown(self): self.assertTrue(drainer._result_unknown(RAISED_RET)) - for ret in (CONFLICT_RET, STATE_FAIL_RET, SUCCESS_RET, ['No minions matched'], {MASTER: 'odd'}, + 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'}, {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], @@ -350,6 +400,21 @@ 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) @@ -431,8 +496,19 @@ 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): - matches = {'G@role:so-sensor': ['sensor_sensor'], 'manager_manager': ['manager_manager']} + 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']} self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {'minions': matches.get(tgt, [])} actions = [ {'state': 'strelka', 'tgt': 'G@role:so-sensor'}, @@ -440,30 +516,503 @@ 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), [actions[0], actions[3]]) + self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'strelka', 'tgt': sensor}, actions[3]], {})) self.CkMinions.assert_called_once() self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [ - ('G@role:so-sensor', 'compound'), ('G@role:so-heavynode', 'compound'), - ('G@role:so-idh', 'compound'), ('manager_manager', 'list'), + (PENDING_TGT, 'compound'), (sensor, 'compound'), (heavynode, 'compound'), (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), actions) + self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'soc', 'tgt': '( * )' + NOT_PENDING}], {})) 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), actions) + self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'soc', 'tgt': '( G@role: )' + NOT_PENDING}], {})) 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): @@ -474,7 +1023,8 @@ 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}), + ('_targeted', {'side_effect': lambda actions, log: (actions, {})}), + ('_master_settling', {'return_value': False}), ): patcher = patch.object(drainer, name, **kwargs) setattr(self, name, patcher.start()) @@ -528,6 +1078,16 @@ 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): @@ -560,7 +1120,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) @@ -570,15 +1130,15 @@ class TestMain(DrainerTestCase): self.assertIn('no action matches a minion; nothing to dispatch', self.logged('info')) def test_dispatches_only_targeted(self): - kept = {'state': 'soc', 'tgt': '*'} - self.intent('mixed.json', actions=[kept, {'state': 'strelka', 'tgt': 'G@role:so-sensor'}]) + matched = {'state': 'soc', 'tgt': '*'} + self.intent('mixed.json', actions=[matched, {'state': 'strelka', 'tgt': 'G@role:so-sensor'}]) self._targeted.side_effect = None - self._targeted.return_value = [kept] + self._targeted.return_value = ([matched], {}) 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], [kept]) - self.assertEqual(record.call_args[0][1], [kept]) + self.assertEqual(dispatch.call_args[0][0], [matched]) + self.assertEqual(record.call_args[0][1], [matched]) if __name__ == '__main__': diff --git a/salt/manager/tools/sbin/so-soup-grid-highstate b/salt/manager/tools/sbin/so-soup-grid-highstate index 1689e5d40..6fc886b1b 100644 --- a/salt/manager/tools/sbin/so-soup-grid-highstate +++ b/salt/manager/tools/sbin/so-soup-grid-highstate @@ -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 ] [--batch-wait ] [--salt-upgraded] [--reason ]" + echo "Usage: so-soup-grid-highstate [--batch ] [--salt-upgraded] [--reason ]" exit 1 } while [ $# -gt 0 ]; do case "$1" in --batch) BATCH="$2"; shift 2 ;; - --batch-wait) BATCH_WAIT="$2"; shift 2 ;; + --batch-wait) IGNORED_BATCH_WAIT=true; shift 2 ;; --salt-upgraded) SALT_UPGRADED=true; shift ;; --reason) REASON="$2"; shift 2 ;; -h|--help) usage ;; @@ -64,6 +64,7 @@ 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. @@ -79,10 +80,6 @@ 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) @@ -100,7 +97,7 @@ if [ "$NUM_ACCEPTED" -le 1 ]; then exit 0 fi -log "starting grid highstate: reason=$REASON minion=$MINIONID accepted=$NUM_ACCEPTED batch=$BATCH batch_wait=$BATCH_WAIT salt_upgraded=$SALT_UPGRADED" +log "starting grid highstate: reason=$REASON minion=$MINIONID accepted=$NUM_ACCEPTED batch=$BATCH salt_upgraded=$SALT_UPGRADED" # Count minions currently responsive on the bus (includes this manager). count_up() { @@ -171,7 +168,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\", \"batch_wait\": $BATCH_WAIT}]" \ + "[{\"highstate\": true, \"tgt\": \"not $MINIONID\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\"}]" \ true log "waiting for minions to reconnect on the new salt version" wait_for_settle "$PRE_UP" @@ -202,7 +199,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\", \"batch_wait\": $BATCH_WAIT}" + actions="$actions{\"highstate\": true, \"tgt\": \"$tgt\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\"}" log "tier matched $n minion(s): $tgt" else log "tier matched 0 minions, skipping: $tgt" diff --git a/salt/manager/tools/sbin/soup b/salt/manager/tools/sbin/soup index b269ddcd1..4b6a6b22b 100755 --- a/salt/manager/tools/sbin/soup +++ b/salt/manager/tools/sbin/soup @@ -1222,6 +1222,7 @@ add_detection_runtime_fields() { ### 3.5.0 Scripts ### up_to_3.5.0() { remove_localrules_portgroup + remove_auto_apply_batch_wait INSTALLEDVERSION=3.5.0 } @@ -1238,8 +1239,26 @@ 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 +} + post_to_3.5.0() { 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" @@ -2416,7 +2435,7 @@ while getopts ":b:f:y" opt; do 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/batch_wait accepts in both forms. + # to so-soup-grid-highstate --batch, which salt's batch 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 diff --git a/salt/orch/push_batch.sls b/salt/orch/push_batch.sls index 2fff2f646..15e02073b 100644 --- a/salt/orch/push_batch.sls +++ b/salt/orch/push_batch.sls @@ -1,26 +1,50 @@ {% from 'salt/auto_apply.map.jinja' import AUTOAPPLY %} {% set actions = salt['pillar.get']('actions', []) %} {% set BATCH = AUTOAPPLY.batch %} -{% set BATCH_WAIT = AUTOAPPLY.batch_wait %} +{# 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 %} {# 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: @@ -29,8 +53,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 %} diff --git a/salt/reactor/pillar_push_map.yaml b/salt/reactor/pillar_push_map.yaml index b49397c30..038b9446a 100644 --- a/salt/reactor/pillar_push_map.yaml +++ b/salt/reactor/pillar_push_map.yaml @@ -3,7 +3,8 @@ # # One pillar directory can map to multiple (state, tgt) actions. # tgt is a raw salt compound expression. tgt_type is always "compound". -# Per-action `batch` / `batch_wait` override the orch defaults (10% / 15s). +# 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%). # An action with `highstate: True` triggers state.highstate instead of # state.apply -- see salt/orch/push_batch.sls. # @@ -98,7 +99,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/batch_wait throttling controls blast radius. +# meaningful. The drainer's batch throttling controls blast radius. global: - highstate: True tgt: '*' diff --git a/salt/reactor/push_pillar.sls b/salt/reactor/push_pillar.sls index 2063a5744..32637de01 100644 --- a/salt/reactor/push_pillar.sls +++ b/salt/reactor/push_pillar.sls @@ -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/batch_wait overrides. + # Preserves the state/highstate selection and any batch override. # 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 = [] diff --git a/salt/salt/cloud/cloud.profiles.d/socloud.conf.jinja b/salt/salt/cloud/cloud.profiles.d/socloud.conf.jinja index 44bef4108..2d068f864 100644 --- a/salt/salt/cloud/cloud.profiles.d/socloud.conf.jinja +++ b/salt/salt/cloud/cloud.profiles.d/socloud.conf.jinja @@ -28,6 +28,8 @@ 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] %} diff --git a/salt/salt/defaults.yaml b/salt/salt/defaults.yaml index a2942ad6e..2f4e2ea5a 100644 --- a/salt/salt/defaults.yaml +++ b/salt/salt/defaults.yaml @@ -4,6 +4,5 @@ salt: debounce_seconds: 30 drain_interval: 15 batch: '10%' - batch_wait: 15 schedule: highstate_interval_minutes: 120 diff --git a/salt/salt/lasthighstate.sls b/salt/salt/lasthighstate.sls index 88d060483..8c93ef7ed 100644 --- a/salt/salt/lasthighstate.sls +++ b/salt/salt/lasthighstate.sls @@ -2,3 +2,12 @@ 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 diff --git a/salt/salt/soc_salt.yaml b/salt/salt/soc_salt.yaml index f3f2ff93a..9563e2529 100644 --- a/salt/salt/soc_salt.yaml +++ b/salt/salt/soc_salt.yaml @@ -3,38 +3,32 @@ 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: push + helpLink: salt 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: push + helpLink: salt 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: push + helpLink: salt 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: push + helpLink: salt 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: push + helpLink: salt global: True advanced: True regex: '^(1[5-9]|[2-9][0-9]|[1-9][0-9]{2,4})$' diff --git a/setup/so-functions b/setup/so-functions index 0381b6252..fed7d9096 100755 --- a/setup/so-functions +++ b/setup/so-functions @@ -519,6 +519,8 @@ 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