actions: reload retains existing action instead of replacing it

Rework as discussed in review: reload keeps every existing action
unconditionally (same instance, neither stopped nor started again).
Changed parameters are applied via reload() if the action supports it,
otherwise (Python action without reload method, e. g. smtp.py) they take
effect after restart of the jail, which is logged now.

Removes the replace path of previous commit (stop of old instance and
restore of current bans for the new one), which is no more needed.
This commit is contained in:
Dv2Corn 2026-11-13 22:21:11 +10:00
parent 06cfe212c4
commit 5bfe1c4d7d
3 changed files with 34 additions and 67 deletions

View file

@ -16,9 +16,10 @@ ver. 1.1.2-dev-1 (20??/??/??) - development nightly edition
* `fail2ban-client reload` resets the jail options removed from configuration to their defaults now: `bantime.increment` and
other `bantime.*` options, `ignoreself`, `ignorecommand`, `ignorecache`, `logtimezone`, `prefregex`, `maxlines` and `datepattern`
retained their previous values until restart of the jail, if they were no more specified in config
* reload handles a Python action without `reload` method (e. g. `smtp.py`) correctly: such action is replaced with new instance,
which was started by every reload, but the previous instance was never stopped and the new one did not know current bans;
now the previous instance is stopped and current bans are executed for the new one as restored tickets (like after restart)
* reload keeps existing actions: a Python action without `reload` method (e. g. `smtp.py`) was replaced with new instance
and started by every reload, but the previous instance was never stopped and the new one did not know current bans;
now the existing instance is retained (neither stopped nor started again), changed parameters of such action
take effect after restart of the jail (logged by reload)
* `fail2ban-client statistic`: format the existing singular alias as the same
statistics table as `stats` and `statistics` (gh-4266).
* backend `pyinotify`: fixes monitoring on systems with native inotify other than Linux (e. g. FreeBSD 15+),

View file

@ -132,34 +132,22 @@ class Actions(JailThread, Mapping):
if name in self._actions:
if not reload:
raise ValueError("Action %s already exists" % name)
# don't create new action if reload supported:
# keep existing action (no new instance, no start/stop), don't execute reload
# right now, reload after all parameters are actualized:
action = self._actions[name]
if hasattr(action, 'reload'):
# don't execute reload right now, reload after all parameters are actualized
if hasattr(action, 'clearAllParams'):
action.clearAllParams()
self._reload_actions[name] = (False, initOpts)
return
if hasattr(action, 'clearAllParams'):
action.clearAllParams()
self._reload_actions[name] = (False, initOpts)
return
## Create new action:
if pythonModule is None:
action = CommandAction(self._jail, name)
else:
customActionModule = self._load_python_module(pythonModule)
action = customActionModule.Action(self._jail, name, **initOpts)
# existing action without reload support gets replaced, so stop it (new one is started
# and gets current bans by end of reload):
replaced = self.active and name in self._actions
if replaced:
try:
self._actions[name].stop()
except Exception as e:
logSys.error("Failed to stop jail '%s' action '%s': %s",
self._jail.name, name, e,
exc_info=logSys.getEffectiveLevel()<=logging.DEBUG)
self._actions[name] = action
if reload:
# to start: 1 - new action, 2 - replaced action
self._reload_actions[name] = (2 if replaced else 1, initOpts)
self._reload_actions[name] = (True, initOpts)
def reload(self, begin=True):
""" Begin or end of reloading resp. refreshing of all parameters
"""
@ -177,10 +165,11 @@ class Actions(JailThread, Mapping):
logSys.error("Failed to start jail '%s' action '%s': %s",
self._jail.name, name, e,
exc_info=logSys.getEffectiveLevel()<=logging.DEBUG)
if startNewAct == 2:
self.__restoreBans(name, self._actions[name])
else:
elif hasattr(self._actions[name], 'reload'):
self._actions[name].reload(**(initOpts if initOpts else {}))
else:
logSys.info("Jail '%s' action '%s' does not support reload, changed "
"parameters take effect after restart of the jail", self._jail.name, name)
# remove obsolete actions (untouched by reload process):
delacts = OrderedDict((name, action) for name, action in self._actions.items()
if name not in self._reload_actions)
@ -584,26 +573,6 @@ class Actions(JailThread, Mapping):
self.banManager.getBanTotal(), self.banManager.size(), self._jail.name)
return cnt
def __restoreBans(self, name, action):
"""Executes ban of all current tickets for the given action only.
Used for the action replaced by reload (previous instance is stopped), the tickets are
handled like tickets restored after restart.
"""
if getattr(action, 'norestored', False):
return
for ticket in self.banManager:
aInfo = self._getActionInfo(ticket)
aInfo['restored'] = 1
try:
action.ban(aInfo)
except Exception as e:
logSys.error(
"Failed to execute ban jail '%s' action '%s' "
"info '%r': %s",
self._jail.name, name, aInfo, e,
exc_info=logSys.getEffectiveLevel()<=logging.DEBUG)
def __reBan(self, ticket, actions=None, log=True):
"""Repeat bans for the ticket.

View file

@ -127,53 +127,50 @@ class ExecuteActions(LogCaptureTestCase):
self.__actions.stopActions()
@with_tmpdir
def testReplacedPythonActionOnReload(self, tmp):
# python action without reload support is replaced by reload with new instance;
# test action logs "<name>-<tag> <method> [<ip> <restored>]", action "nores" has norestored set:
def testExistingPythonActionWithoutReloadRetainedOnReload(self, tmp):
# python action without reload method (like smtp.py) is retained by reload (same instance,
# neither stopped nor started again); test action logs "<name>-<tag> <method> [<ip>]":
pyact = os.path.join(tmp, 'action.py')
with open(pyact, 'w') as f:
f.write("\n".join((
"from fail2ban.server.action import ActionBase",
"class Action(ActionBase):",
" def __init__(self, jail, name, tag, norestored=0):",
" def __init__(self, jail, name, tag):",
" super(Action, self).__init__(jail, name)",
" if norestored: self.norestored = 1",
" self._pref = '%s-%s' % (name, tag)",
" def start(self): self._logSys.info('%s start', self._pref)",
" def stop(self): self._logSys.info('%s stop', self._pref)",
" def ban(self, aInfo): self._logSys.info('%s ban %s %s', self._pref, aInfo['ip'], aInfo['restored'])",
" def ban(self, aInfo): self._logSys.info('%s ban %s', self._pref, aInfo['ip'])",
" def unban(self, aInfo): self._logSys.info('%s unban %s', self._pref, aInfo['ip'])",
""
)))
self.__actions.add('act', pyact, {'tag': 'old'})
self.__actions.add('other')
self.__actions.add('nores', pyact, {'tag': 'old', 'norestored': 1})
act = self.__actions['act']
self.assertFalse(hasattr(act, 'reload'))
self.__actions.start()
self.assertLogged('act-old start', 'nores-old start', all=True, wait=True)
self.assertLogged('act-old start', wait=True)
self.__actions.addBannedIP('192.0.2.1')
self.assertLogged('act-old ban 192.0.2.1 0', 'nores-old ban 192.0.2.1 0', all=True)
self.assertLogged('act-old ban 192.0.2.1')
self.pruneLog('[test-phase] reload')
self.__actions.reload(begin=True)
self.__actions.add('act', pyact, {'tag': 'new'}, reload=True)
self.__actions.add('other', reload=True)
self.__actions.add('nores', pyact, {'tag': 'new', 'norestored': 1}, reload=True)
# old instances are stopped, new ones are not started yet:
self.assertLogged('act-old stop', 'nores-old stop', all=True)
self.assertNotLogged('act-new start', 'nores-new start', all=True)
self.__actions.reload(begin=False)
# new instances are started, current ban is executed again as restored (if not norestored):
self.assertLogged('act-new start', 'act-new ban 192.0.2.1 1', 'nores-new start', all=True)
self.assertNotLogged('nores-new ban', 'unban 192.0.2.1', all=True)
# position of actions is retained:
self.assertEqual(list(self.__actions), ['act', 'other', 'nores'])
# further bans and unban (by stop) with new instances only:
# same instance, not stopped, not started again, no new instance created:
self.assertIs(self.__actions['act'], act)
self.assertNotLogged('act-old stop', 'act-old start', 'act-new', all=True)
self.assertLogged("Jail 'DummyJail' action 'act' does not support reload, changed "
"parameters take effect after restart of the jail")
self.assertEqual(list(self.__actions), ['act', 'other'])
# further bans reach the retained instance, stop unbans all and stops it once:
self.pruneLog('[test-phase] after reload')
self.__actions.addBannedIP('192.0.2.2')
self.assertLogged('act-new ban 192.0.2.2 0', 'nores-new ban 192.0.2.2 0', all=True)
self.assertLogged('act-old ban 192.0.2.2')
self.__actions.stop()
self.__actions.join()
self.assertLogged('act-new unban 192.0.2.1', 'act-new unban 192.0.2.2', 'act-new stop', 'nores-new stop', all=True)
self.assertNotLogged('act-old', 'nores-old', all=True)
self.assertLogged('act-old unban 192.0.2.1', 'act-old unban 192.0.2.2', 'act-old stop', all=True)
self.assertNotLogged('act-new', all=True)
def testRepeatedReloadDoesNotRestartNewAction(self):
self.__actions.reload(begin=True)