summaryrefslogtreecommitdiff
path: root/fail2ban/tests/fail2banclienttestcase.py
blob: 0cbda94f9a1d204c3a599d09878e746d9f1cec60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :

# This file is part of Fail2Ban.
#
# Fail2Ban is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Fail2Ban is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fail2Ban; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# Fail2Ban developers

__author__ = "Serg Brester"
__copyright__ = "Copyright (c) 2014- Serg G. Brester (sebres), 2008- Fail2Ban Contributors"
__license__ = "GPL"

import fileinput
import os
import re
import sys
import time
import signal
import unittest

from os.path import join as pjoin, isdir, isfile, exists, dirname
from functools import wraps
from threading import Thread

from ..client import fail2banclient, fail2banserver, fail2bancmdline
from ..client.fail2bancmdline import Fail2banCmdLine
from ..client.fail2banclient import exec_command_line as _exec_client, CSocket, VisualWait
from ..client.fail2banserver import Fail2banServer, exec_command_line as _exec_server
from .. import protocol
from ..server import server
from ..server.mytime import MyTime
from ..server.utils import Utils
from .utils import LogCaptureTestCase, logSys as DefLogSys, with_tmpdir, shutil, logging, \
	STOCK, CONFIG_DIR as STOCK_CONF_DIR, TEST_NOW, tearDownMyTime

from ..helpers import getLogger

# Gets the instance of the logger.
logSys = getLogger(__name__)

CLIENT = "fail2ban-client"
SERVER = "fail2ban-server"
BIN = dirname(Fail2banServer.getServerPath())

MAX_WAITTIME = unittest.F2B.maxWaitTime(unittest.F2B.MAX_WAITTIME)
MID_WAITTIME = unittest.F2B.maxWaitTime(unittest.F2B.MID_WAITTIME)

##
# Several wrappers and settings for proper testing:
#

fail2bancmdline.MAX_WAITTIME = MAX_WAITTIME - 1

fail2bancmdline.logSys = \
fail2banclient.logSys = \
fail2banserver.logSys = logSys

SRV_DEF_LOGTARGET = server.DEF_LOGTARGET
SRV_DEF_LOGLEVEL = server.DEF_LOGLEVEL

def _test_output(*args):
	logSys.info(args[0])
fail2bancmdline.output = \
fail2banclient.output = \
fail2banserver.output = \
protocol.output = _test_output

def _time_shift(shift):
	# jump to the future (+shift minutes):
	logSys.debug("===>>> time shift + %s min", shift)
	MyTime.setTime(MyTime.time() + shift*60)


Observers = server.Observers

def _observer_wait_idle():
	"""Helper to wait observer becomes idle"""
	if Observers.Main is not None:
		Observers.Main.wait_empty(MID_WAITTIME)
		Observers.Main.wait_idle(MID_WAITTIME / 5)

def _observer_wait_before_incrban(cond, timeout=MID_WAITTIME):
	"""Helper to block observer before increase bantime until some condition gets true"""
	if Observers.Main is not None:
		# switch ban handler:
		_obs_banFound = Observers.Main.banFound
		def _banFound(*args, **kwargs):
			# restore original handler:
			Observers.Main.banFound = _obs_banFound
			# wait for:
			logSys.debug('  [Observer::banFound] *** observer blocked for test')
			Utils.wait_for(cond, timeout)
			logSys.debug('  [Observer::banFound] +++ observer runs again')
			# original banFound:
			_obs_banFound(*args, **kwargs)
		Observers.Main.banFound = _banFound

#
# Mocking .exit so we could test its correct operation.
# Two custom exceptions will be assessed to be raised in the tests
#

class ExitException(fail2bancmdline.ExitException):
	"""Exception upon a normal exit"""
	pass


class FailExitException(fail2bancmdline.ExitException):
	"""Exception upon abnormal exit"""
	pass


SUCCESS = ExitException
FAILED = FailExitException

INTERACT = []


def _test_input_command(*args):
	if len(INTERACT):
		#logSys.debug('--- interact command: %r', INTERACT[0])
		return INTERACT.pop(0)
	else:
		return "exit"

fail2banclient.input_command = _test_input_command

# prevents change logging params, log capturing, etc:
fail2bancmdline.PRODUCTION = \
fail2banserver.PRODUCTION = False

_out_file = LogCaptureTestCase.dumpFile

def _write_file(fn, mode, *lines):
	f = open(fn, mode)
	f.write('\n'.join(lines)+('\n' if lines else ''))
	f.close()

def _read_file(fn):
	f = None
	try:
		f = open(fn)
		return f.read()
	finally:
		if f is not None:
			f.close()


def _start_params(tmp, use_stock=False, use_stock_cfg=None, 
	logtarget="/dev/null", db=":memory:", f2b_local=(), jails=("",), 
	create_before_start=None,
):
	cfg = pjoin(tmp, "config")
	if db == 'auto':
		db = pjoin(tmp, "f2b-db.sqlite3")
	j_conf = 'jail.conf'
	if use_stock and STOCK:
		# copy config (sub-directories as alias):
		def ig_dirs(dir, files):
			"""Filters list of 'files' to contain only directories (under dir)"""
			return [f for f in files if isdir(pjoin(dir, f))]
		shutil.copytree(STOCK_CONF_DIR, cfg, ignore=ig_dirs)
		if use_stock_cfg is None: use_stock_cfg = ('action.d', 'filter.d')
		# replace fail2ban params (database with memory):
		r = re.compile(r'^dbfile\s*=')
		for line in fileinput.input(pjoin(cfg, "fail2ban.conf"), inplace=True):
			line = line.rstrip('\n')
			if r.match(line):
				line = "dbfile = :memory:"
			print(line)
		# replace jail params (polling as backend to be fast in initialize):
		r = re.compile(r'^backend\s*=')
		for line in fileinput.input(pjoin(cfg, "jail.conf"), inplace=True):
			line = line.rstrip('\n')
			if r.match(line):
				line = "backend = polling"
			print(line)
		# jails to local:
		j_conf = 'jail.local' if jails else ''
	else:
		# just empty config directory without anything (only fail2ban.conf/jail.conf):
		os.mkdir(cfg)
		_write_file(pjoin(cfg, "fail2ban.conf"), "w",
			"[Definition]",
			"loglevel = INFO",
			"logtarget = " + logtarget.replace('%', '%%'),
			"syslogsocket = auto",
			"socket = " + pjoin(tmp, "f2b.sock"),
			"pidfile = " + pjoin(tmp, "f2b.pid"),
			"backend = polling",
			"dbfile = " + db,
			"dbmaxmatches = 100",
			"dbpurgeage = 1d",
			"",
		)
	# write jails (local or conf):
	if j_conf:
		_write_file(pjoin(cfg, j_conf), "w",
			*((
				"[INCLUDES]", "",
			  "[DEFAULT]", "tmp = " + tmp, "",
			)+jails)
		)
	if f2b_local:
		_write_file(pjoin(cfg, "fail2ban.local"), "w", *f2b_local)
	if unittest.F2B.log_level < logging.DEBUG: # pragma: no cover
		_out_file(pjoin(cfg, "fail2ban.conf"))
		_out_file(pjoin(cfg, "jail.conf"))
		if f2b_local:
			_out_file(pjoin(cfg, "fail2ban.local"))
		if j_conf and j_conf != "jail.conf":
			_out_file(pjoin(cfg, j_conf))

	# link stock actions and filters:
	if use_stock_cfg and STOCK:
		for n in use_stock_cfg:
			os.symlink(os.path.abspath(pjoin(STOCK_CONF_DIR, n)), pjoin(cfg, n))
	if create_before_start:
		for n in create_before_start:
			_write_file(n % {'tmp': tmp}, 'w')
	# parameters (sock/pid and config, increase verbosity, set log, etc.):
	vvv, llev = (), "INFO"
	if unittest.F2B.log_level < logging.INFO: # pragma: no cover
		llev = str(unittest.F2B.log_level)
		if unittest.F2B.verbosity > 1:
			vvv = ("-" + "v"*unittest.F2B.verbosity,)
	llev = vvv + ("--loglevel", llev)
	return (
		"-c", cfg, "-s", pjoin(tmp, "f2b.sock"), "-p", pjoin(tmp, "f2b.pid"),
		"--logtarget", logtarget,) + llev + ("--syslogsocket", "auto",
		"--timeout", str(fail2bancmdline.MAX_WAITTIME),
	)

def _inherited_log(startparams):
	try:
		return startparams[startparams.index('--logtarget')+1] == 'INHERITED'
	except ValueError:
		return False

def _get_pid_from_file(pidfile):
	pid = None
	try:
		pid = _read_file(pidfile)
		pid = re.match(r'\S+', pid).group()
		return int(pid)
	except Exception as e: # pragma: no cover
		logSys.debug(e)
	return pid

def _kill_srv(pidfile):
	logSys.debug("cleanup: %r", (pidfile, isdir(pidfile)))
	if isdir(pidfile):
		piddir = pidfile
		pidfile = pjoin(piddir, "f2b.pid")
		if not isfile(pidfile): # pragma: no cover
			pidfile = pjoin(piddir, "fail2ban.pid")

	# output log in heavydebug (to see possible start errors):
	if unittest.F2B.log_level < logging.DEBUG: # pragma: no cover
		logfile = pjoin(piddir, "f2b.log")
		if isfile(logfile):
			_out_file(logfile)
		else:
			logSys.log(5, 'no logfile %r', logfile)

	if not isfile(pidfile):
		logSys.debug("cleanup: no pidfile for %r", piddir)
		return True

	logSys.debug("cleanup pidfile: %r", pidfile)
	pid = _get_pid_from_file(pidfile)
	if pid is None: # pragma: no cover
		return False

	try:
		logSys.debug("cleanup pid: %r", pid)
		if pid <= 0 or pid == os.getpid(): # pragma: no cover
			raise ValueError('pid %s of %s is invalid' % (pid, pidfile))
		if not Utils.pid_exists(pid):
			return True
		## try to properly stop (have signal handler):
		os.kill(pid, signal.SIGTERM)
		## check still exists after small timeout:
		if not Utils.wait_for(lambda: not Utils.pid_exists(pid), 1):
			## try to kill hereafter:
			os.kill(pid, signal.SIGKILL)
		logSys.debug("cleanup: kill ready")
		return not Utils.pid_exists(pid)
	except Exception as e: # pragma: no cover
		logSys.exception(e)
	return True


def with_kill_srv(f):
	"""Helper to decorate tests which receive in the last argument tmpdir to pass to kill_srv

	To be used in tandem with @with_tmpdir
	"""
	@wraps(f)
	def wrapper(self, *args):
		pidfile = args[-1]
		try:
			return f(self, *args)
		finally:
			_kill_srv(pidfile)
	return wrapper

def with_foreground_server_thread(startextra={}):
	"""Helper to decorate tests uses foreground server (as thread), started directly in test-cases

	To be used only in subclasses
	"""
	def _deco_wrapper(f):
		@with_tmpdir
		@wraps(f)
		def wrapper(self, tmp, *args, **kwargs):
			th = None
			phase = dict()
			try:
				# started directly here, so prevent overwrite test cases logger with "INHERITED"
				startparams = _start_params(tmp, logtarget="INHERITED", **startextra)
				# because foreground block execution - start it in thread:
				th = Thread(
					name="_TestCaseWorker",
					target=self._testStartForeground,
					args=(tmp, startparams, phase)
				)
				th.daemon = True
				th.start()
				# to wait for end of server, default accept any exit code, because multi-threaded, 
				# thus server can exit in-between...
				def _stopAndWaitForServerEnd(code=(SUCCESS, FAILED)):
					tearDownMyTime()
					# if seems to be down - try to catch end phase (wait a bit for end:True to recognize down state):
					if not phase.get('end', None) and not os.path.exists(pjoin(tmp, "f2b.pid")):
						Utils.wait_for(lambda: phase.get('end', None) is not None, MID_WAITTIME)
					# stop (if still running):
					if not phase.get('end', None):
						self.execCmd(code, startparams, "stop")
						# wait for end sign:
						Utils.wait_for(lambda: phase.get('end', None) is not None, MAX_WAITTIME)
						self.assertTrue(phase.get('end', None))
						self.assertLogged("Shutdown successful", "Exiting Fail2ban", all=True, wait=MAX_WAITTIME)
					# set to NOP: avoid dual call
					self.stopAndWaitForServerEnd = lambda *args, **kwargs: None
				self.stopAndWaitForServerEnd = _stopAndWaitForServerEnd
				# wait for start thread:
				Utils.wait_for(lambda: phase.get('start', None) is not None, MAX_WAITTIME)
				self.assertTrue(phase.get('start', None))
				# wait for server (socket and ready):
				self._wait_for_srv(tmp, True, startparams=startparams, phase=phase)
				DefLogSys.info('=== within server: begin ===')
				self.pruneLog()
				# several commands to server in body of decorated function:
				return f(self, tmp, startparams, *args, **kwargs)
			except Exception as e: # pragma: no cover
				print('=== Catch an exception: %s' % e)
				log = self.getLog()
				if log:
					print('=== Error of server, log: ===\n%s===' % log)
					self.pruneLog()
				raise
			finally:
				if th:
					# wait for server end (if not yet already exited):
					DefLogSys.info('=== within server: end.  ===')
					self.pruneLog()
					self.stopAndWaitForServerEnd()
					# we start client/server directly in current process (new thread),
					# so don't kill (same process) - if success, just wait for end of worker:
					if phase.get('end', None):
						th.join()
				tearDownMyTime()
		return wrapper
	return _deco_wrapper


class Fail2banClientServerBase(LogCaptureTestCase):

	_orig_exit = Fail2banCmdLine._exit

	def _setLogLevel(self, *args, **kwargs):
		pass

	def setUp(self):
		"""Call before every test case."""
		LogCaptureTestCase.setUp(self)
		# prevent to switch the logging in the test cases (use inherited one):
		server.DEF_LOGTARGET = "INHERITED"
		server.DEF_LOGLEVEL = DefLogSys.level
		Fail2banCmdLine._exit = staticmethod(self._test_exit)

	def tearDown(self):
		"""Call after every test case."""
		Fail2banCmdLine._exit = self._orig_exit
		# restore server log target:
		server.DEF_LOGTARGET = SRV_DEF_LOGTARGET
		server.DEF_LOGLEVEL = SRV_DEF_LOGLEVEL
		LogCaptureTestCase.tearDown(self)
		tearDownMyTime()

	@staticmethod
	def _test_exit(code=0):
		if code == 0:
			raise ExitException()
		else:
			raise FailExitException()

	def _wait_for_srv(self, tmp, ready=True, startparams=None, phase=None):
		if not phase: phase = {}
		try:
			sock = pjoin(tmp, "f2b.sock")
			# wait for server (socket):
			ret = Utils.wait_for(lambda: phase.get('end') or exists(sock), MAX_WAITTIME)
			if not ret or phase.get('end'): # pragma: no cover - test-failure case only
				raise Exception(
					'Unexpected: Socket file does not exists.\nStart failed: %r'
					% (startparams,)
				)
			if ready:
				# wait for communication with worker ready:
				ret = Utils.wait_for(lambda: "Server ready" in self.getLog(), MAX_WAITTIME)
				if not ret: # pragma: no cover - test-failure case only
					raise Exception(
						'Unexpected: Server ready was not found, phase %r.\nStart failed: %r'
						% (phase, startparams,)
					)
		except:  # pragma: no cover
			if _inherited_log(startparams):
				print('=== Error by wait fot server, log: ===\n%s===' % self.getLog())
				self.pruneLog()
			log = pjoin(tmp, "f2b.log")
			if isfile(log):
				_out_file(log)
			elif not _inherited_log(startparams):
				logSys.debug("No log file %s to examine details of error", log)
			raise

	def execCmd(self, exitType, startparams, *args):
		self.assertRaises(exitType, self.exec_command_line[0],
			(self.exec_command_line[1:] + startparams + args))

	def execCmdDirect(self, startparams, *args):
		sock = startparams[startparams.index('-s')+1]
		s = CSocket(sock)
		try:
			return s.send(args)
		finally:
			s.close()

	#
	# Common tests
	#
	def _testStartForeground(self, tmp, startparams, phase):
		# start and wait to end (foreground):
		logSys.debug("start of test worker")
		phase['start'] = True
		try:
			self.execCmd(SUCCESS, ("-f",) + startparams, "start")
		finally:
			# end :
			phase['start'] = False
			phase['end'] = True
			logSys.debug("end of test worker")

	@with_foreground_server_thread(startextra={'f2b_local':(
			"[Thread]",
			"stacksize = 128"
			"",
		)})
	def testStartForeground(self, tmp, startparams):
		# check thread options were set:
		self.pruneLog()
		self.execCmd(SUCCESS, startparams, "get", "thread")
		self.assertLogged("{'stacksize': 128}")
		# several commands to server:
		self.execCmd(SUCCESS, startparams, "ping")
		self.execCmd(FAILED, startparams, "~~unknown~cmd~failed~~")
		self.execCmd(SUCCESS, startparams, "echo", "TEST-ECHO")


class Fail2banClientTest(Fail2banClientServerBase):

	exec_command_line = (_exec_client, CLIENT,)

	def testConsistency(self):
		self.assertTrue(isfile(pjoin(BIN, CLIENT)))
		self.assertTrue(isfile(pjoin(BIN, SERVER)))

	def testClientUsage(self):
		self.execCmd(SUCCESS, (), "-h")
		self.assertLogged("Usage: " + CLIENT)
		self.assertLogged("Report bugs to ")
		self.pruneLog()
		self.execCmd(SUCCESS, (), "-V")
		self.assertLogged(fail2bancmdline.normVersion())
		self.pruneLog()
		self.execCmd(SUCCESS, (), "-vq", "--version")
		self.assertLogged("Fail2Ban v" + fail2bancmdline.version)
		self.pruneLog()
		self.execCmd(SUCCESS, (), "--str2sec", "1d12h30m")
		self.assertLogged("131400")

	@with_tmpdir
	def testClientDump(self, tmp):
		# use here the stock configuration (if possible)
		startparams = _start_params(tmp, True)
		self.execCmd(SUCCESS, startparams, "-vvd")
		self.assertLogged("Loading files")
		self.assertLogged("['set', 'logtarget',")
		self.pruneLog()
		# pretty dump:
		self.execCmd(SUCCESS, startparams, "--dp")
		self.assertLogged("['set', 'logtarget',")
		
	@with_tmpdir
	@with_kill_srv
	def testClientStartBackgroundInside(self, tmp):
		# use once the stock configuration (to test starting also)
		startparams = _start_params(tmp, True)
		# start:
		self.execCmd(SUCCESS, ("-b",) + startparams, "start")
		# wait for server (socket and ready):
		self._wait_for_srv(tmp, True, startparams=startparams)
		self.assertLogged("Server ready")
		self.assertLogged("Exit with code 0")
		try:
			self.execCmd(SUCCESS, startparams, "echo", "TEST-ECHO")
			self.execCmd(FAILED, startparams, "~~unknown~cmd~failed~~")
			self.pruneLog()
			# start again (should fail):
			self.execCmd(FAILED, ("-b",) + startparams, "start")
			self.assertLogged("Server already running")
		finally:
			self.pruneLog()
			# stop:
			self.execCmd(SUCCESS, startparams, "stop")
			self.assertLogged("Shutdown successful")
			self.assertLogged("Exit with code 0")

		self.pruneLog()
		# stop again (should fail):
		self.execCmd(FAILED, startparams, "stop")
		self.assertLogged("Failed to access socket path")
		self.assertLogged("Is fail2ban running?")

	@with_tmpdir
	@with_kill_srv
	def testClientStartBackgroundCall(self, tmp):
		global INTERACT
		startparams = _start_params(tmp, logtarget=pjoin(tmp, "f2b.log"))
		# if fast, start server process from client started direct here:
		if unittest.F2B.fast: # pragma: no cover
			self.execCmd(SUCCESS, startparams + ("start",))
		else:
			# start (in new process, using the same python version):
			cmd = (sys.executable, pjoin(BIN, CLIENT))
			logSys.debug('Start %s ...', cmd)
			cmd = cmd + startparams + ("--async", "start",)
			ret = Utils.executeCmd(cmd, timeout=MAX_WAITTIME, shell=False, output=True)
			self.assertTrue(len(ret) and ret[0])
			# wait for server (socket and ready):
			self._wait_for_srv(tmp, True, startparams=cmd)
		self.assertLogged("Server ready")
		self.pruneLog()
		try:
			# echo from client (inside):
			self.execCmd(SUCCESS, startparams, "echo", "TEST-ECHO")
			self.assertLogged("TEST-ECHO")
			self.assertLogged("Exit with code 0")
			self.pruneLog()
			# test ping timeout:
			self.execCmd(SUCCESS, startparams, "ping", "0.1")
			self.assertLogged("Server replied: pong")
			self.pruneLog()
			# python 3 seems to bypass such short timeouts also, 
			# so suspend/resume server process and test between it...
			pid = _get_pid_from_file(pjoin(tmp, "f2b.pid"))
			try:
				# suspend:
				os.kill(pid, signal.SIGSTOP); # or SIGTSTP?
				time.sleep(Utils.DEFAULT_SHORT_INTERVAL)
				# test ping with short timeout:
				self.execCmd(FAILED, startparams, "ping", "1e-10")
			finally:
				# resume:
				os.kill(pid, signal.SIGCONT)
			self.assertLogged("timed out")
			self.pruneLog()
			# interactive client chat with started server:
			INTERACT += [
				"echo INTERACT-ECHO",
				"status",
				"exit"
			]
			self.execCmd(SUCCESS, startparams, "-i")
			self.assertLogged("INTERACT-ECHO")
			self.assertLogged("Status", "Number of jail:")
			self.assertLogged("Exit with code 0")
			self.pruneLog()
			# test reload and restart over interactive client:
			INTERACT += [
				"reload",
				"restart",
				"exit"
			]
			self.execCmd(SUCCESS, startparams, "-i")
			self.assertLogged("Reading config files:")
			self.assertLogged("Shutdown successful")
			self.assertLogged("Server ready")
			self.assertLogged("Exit with code 0")
			self.pruneLog()
			# test reload missing jail (interactive):
			INTERACT += [
				"reload ~~unknown~jail~fail~~",
				"exit"
			]
			self.execCmd(SUCCESS, startparams, "-i")
			self.assertLogged("Failed during configuration: No section: '~~unknown~jail~fail~~'")
			self.pruneLog()
			# test reload missing jail (direct):
			self.execCmd(FAILED, startparams, "reload", "~~unknown~jail~fail~~")
			self.assertLogged("Failed during configuration: No section: '~~unknown~jail~fail~~'")
			self.assertLogged("Exit with code 255")
			self.pruneLog()
		finally:
			self.pruneLog()
			# stop:
			self.execCmd(SUCCESS, startparams, "stop")
			self.assertLogged("Shutdown successful")
			self.assertLogged("Exit with code 0")

	@with_tmpdir
	@with_kill_srv
	def testClientFailStart(self, tmp):
		# started directly here, so prevent overwrite test cases logger with "INHERITED"
		startparams = _start_params(tmp, logtarget="INHERITED")

		## wrong config directory
		self.execCmd(FAILED, (),
			"--async", "-c", pjoin(tmp, "miss"), "start")
		self.assertLogged("Base configuration directory " + pjoin(tmp, "miss") + " does not exist")
		self.pruneLog()

		## not running
		self.execCmd(FAILED, (),
			"-c", pjoin(tmp, "config"), "-s", pjoin(tmp, "f2b.sock"), "reload")
		self.assertLogged("Could not find server")
		self.pruneLog()

		## already exists:
		open(pjoin(tmp, "f2b.sock"), 'a').close()
		self.execCmd(FAILED, (),
			"--async", "-c", pjoin(tmp, "config"), "-s", pjoin(tmp, "f2b.sock"), "start")
		self.assertLogged("Fail2ban seems to be in unexpected state (not running but the socket exists)")
		self.pruneLog()
		os.remove(pjoin(tmp, "f2b.sock"))

		## wrong option:
		self.execCmd(FAILED, (), "-s")
		self.assertLogged("Usage: ")
		self.pruneLog()

	@with_tmpdir
	def testClientFailCommands(self, tmp):
		# started directly here, so prevent overwrite test cases logger with "INHERITED"
		startparams = _start_params(tmp, logtarget="INHERITED")

		# not started:
		self.execCmd(FAILED, startparams,
			"reload", "jail")
		self.assertLogged("Could not find server")
		self.pruneLog()

		# unexpected arg:
		self.execCmd(FAILED, startparams,
			"--async", "reload", "--xxx", "jail")
		self.assertLogged("Unexpected argument(s) for reload:")
		self.pruneLog()


	def testVisualWait(self):
		sleeptime = 0.035
		for verbose in (2, 0):
			cntr = 15
			with VisualWait(verbose, 5) as vis:
				while cntr:
					vis.heartbeat()
					if verbose and not unittest.F2B.fast:
						time.sleep(sleeptime)
					cntr -= 1


class Fail2banServerTest(Fail2banClientServerBase):

	exec_command_line = (_exec_server, SERVER,)

	def testServerUsage(self):
		self.execCmd(SUCCESS, (), "-h")
		self.assertLogged("Usage: " + SERVER)
		self.assertLogged("Report bugs to ")

	@with_tmpdir
	@with_kill_srv
	def testServerStartBackground(self, tmp):
		# to prevent fork of test-cases process, start server in background via command:
		startparams = _start_params(tmp, logtarget=pjoin(tmp, "f2b.log"))
		# start (in new process, using the same python version):
		cmd = (sys.executable, pjoin(BIN, SERVER))
		logSys.debug('Start %s ...', cmd)
		cmd = cmd + startparams + ("-b",)
		ret = Utils.executeCmd(cmd, timeout=MAX_WAITTIME, shell=False, output=True)
		self.assertTrue(len(ret) and ret[0])
		# wait for server (socket and ready):
		self._wait_for_srv(tmp, True, startparams=cmd)
		self.assertLogged("Server ready")
		self.pruneLog()
		try:
			self.execCmd(SUCCESS, startparams, "echo", "TEST-ECHO")
			self.execCmd(FAILED, startparams, "~~unknown~cmd~failed~~")
		finally:
			self.pruneLog()
			# stop:
			self.execCmd(SUCCESS, startparams, "stop")
			self.assertLogged("Shutdown successful")
			self.assertLogged("Exit with code 0")

	@with_tmpdir
	@with_kill_srv
	def testServerFailStart(self, tmp):
		# started directly here, so prevent overwrite test cases logger with "INHERITED"
		startparams = _start_params(tmp, logtarget="INHERITED")

		## wrong config directory
		self.execCmd(FAILED, (),
			"-c", pjoin(tmp, "miss"))
		self.assertLogged("Base configuration directory " + pjoin(tmp, "miss") + " does not exist")
		self.pruneLog()

		## already exists:
		open(pjoin(tmp, "f2b.sock"), 'a').close()
		self.execCmd(FAILED, (),
			"-c", pjoin(tmp, "config"), "-s", pjoin(tmp, "f2b.sock"))
		self.assertLogged("Fail2ban seems to be in unexpected state (not running but the socket exists)")
		self.pruneLog()
		os.remove(pjoin(tmp, "f2b.sock"))

	@with_tmpdir
	@with_kill_srv
	def testServerTestFailStart(self, tmp):
		# started directly here, so prevent overwrite test cases logger with "INHERITED"
		startparams = _start_params(tmp, logtarget="INHERITED")
		cfg = pjoin(tmp, "config")

		# test configuration is correct:
		self.pruneLog("[test-phase 0]")
		self.execCmd(SUCCESS, startparams, "--test")
		self.assertLogged("OK: configuration test is successful")

		# append one wrong configured jail:
		_write_file(pjoin(cfg, "jail.conf"), "a", "", "[broken-jail]", 
			"", "filter = broken-jail-filter", "enabled = true")

		# first try test config:
		self.pruneLog("[test-phase 0a]")
		self.execCmd(FAILED, startparams, "--test")
		self.assertLogged("Unable to read the filter 'broken-jail-filter'",
			"Errors in jail 'broken-jail'.",
			"ERROR: test configuration failed", all=True)

		# failed to start with test config:
		self.pruneLog("[test-phase 0b]")
		self.execCmd(FAILED, startparams, "-t", "start")
		self.assertLogged("Unable to read the filter 'broken-jail-filter'",
			"Errors in jail 'broken-jail'.",
			"ERROR: test configuration failed", all=True)

	@with_tmpdir
	def testKillAfterStart(self, tmp):
		try:
			# to prevent fork of test-cases process, start server in background via command:
			startparams = _start_params(tmp, logtarget=pjoin(tmp,
				'f2b.log[format="SRV: %(relativeCreated)3d | %(message)s", datetime=off]'))
			# start (in new process, using the same python version):
			cmd = (sys.executable, pjoin(BIN, SERVER))
			logSys.debug('Start %s ...', cmd)
			cmd = cmd + startparams + ("-b",)
			ret = Utils.executeCmd(cmd, timeout=MAX_WAITTIME, shell=False, output=True)
			self.assertTrue(len(ret) and ret[0])
			# wait for server (socket and ready):
			self._wait_for_srv(tmp, True, startparams=cmd)
			self.assertLogged("Server ready")
			self.pruneLog()
			logSys.debug('Kill server ... %s', tmp)
		finally:
			self.assertTrue(_kill_srv(tmp))
		# wait for end (kill was successful):
		Utils.wait_for(lambda: not isfile(pjoin(tmp, "f2b.pid")), MAX_WAITTIME)
		self.assertFalse(isfile(pjoin(tmp, "f2b.pid")))
		self.assertLogged("cleanup: kill ready")
		self.pruneLog()
		# again:
		self.assertTrue(_kill_srv(tmp))
		self.assertLogged("cleanup: no pidfile for")

	@with_foreground_server_thread(startextra={'db': 'auto'})
	def testServerReloadTest(self, tmp, startparams):
		# Very complicated test-case, that expected running server (foreground in thread).
		#
		# In this test-case, each phase is related from previous one, 
		# so it cannot be splitted in multiple test cases.
		# Additionaly many log-messages used as ready-sign (to wait for end of phase).
		#
		# Used file database (instead of :memory:), to restore bans and log-file positions,
		# after restart/reload between phases.
		cfg = pjoin(tmp, "config")
		test1log = pjoin(tmp, "test1.log")
		test2log = pjoin(tmp, "test2.log")
		test3log = pjoin(tmp, "test3.log")

		os.mkdir(pjoin(cfg, "action.d"))
		def _write_action_cfg(actname="test-action1", allow=True, 
			start="", reload="", ban="", unban="", stop=""):
			fn = pjoin(cfg, "action.d", "%s.conf" % actname)
			if not allow:
				os.remove(fn)
				return
			_write_file(fn, "w",
				"[DEFAULT]",
				"_exec_once = 0",
				"",
				"[Definition]",
				"norestored = %(_exec_once)s",
				"restore = ",
				"info = ",
				"_use_flush_ = echo '[%(name)s] %(actname)s: -- flushing IPs'",
				"actionstart =  echo '[%(name)s] %(actname)s: ** start'", start,
				"actionreload = echo '[%(name)s] %(actname)s: .. reload'", reload,
				"actionban =    echo '[%(name)s] %(actname)s: ++ ban <ip> %(restore)s%(info)s'", ban,
				"actionunban =  echo '[%(name)s] %(actname)s: -- unban <ip>'", unban,
				"actionstop =   echo '[%(name)s] %(actname)s: __ stop'", stop,
			)
			if unittest.F2B.log_level <= logging.DEBUG: # pragma: no cover
				_out_file(fn)

		def _write_jail_cfg(enabled=(1, 2), actions=(), backend="polling"):
			_write_file(pjoin(cfg, "jail.conf"), "w",
				"[INCLUDES]", "",
				"[DEFAULT]", "",
				"usedns = no",
				"maxretry = 3",
				"findtime = 10m",
				r"failregex = ^\s*failure <F-ERRCODE>401|403</F-ERRCODE> from <HOST>",
				"datepattern = {^LN-BEG}EPOCH",
				"ignoreip = 127.0.0.1/8 ::1", # just to cover ignoreip in jailreader/transmitter
				"",
				"[test-jail1]", "backend = " + backend, "filter =", 
				"action = ",
				"         test-action1[name='%(__name__)s']" \
					if 1 in actions else "",
				"         test-action2[name='%(__name__)s', restore='restored: <restored>', info=', err-code: <F-ERRCODE>']" \
					if 2 in actions else "",
				"         test-action2[name='%(__name__)s', actname=test-action3, _exec_once=1, restore='restored: <restored>',"
										" actionflush=<_use_flush_>]" \
					if 3 in actions else "",
				"logpath = " + test1log,
				"          " + test2log if 2 in enabled else "",
				"          " + test3log if 2 in enabled else "",
				r"failregex = ^\s*failure <F-ERRCODE>401|403</F-ERRCODE> from <HOST>",
				r"            ^\s*error <F-ERRCODE>401|403</F-ERRCODE> from <HOST>" \
					if 2 in enabled else "",
				"enabled = true" if 1 in enabled else "",
				"",
				"[test-jail2]", "backend = " + backend, "filter =", 
				"action = ",
				"         test-action2[name='%(__name__)s', restore='restored: <restored>', info=', err-code: <F-ERRCODE>']" \
					if 2 in actions else "",
				"         test-action2[name='%(__name__)s', actname=test-action3, _exec_once=1, restore='restored: <restored>',"
										" actionflush=<_use_flush_>]" \
					if 3 in actions else "",
				"logpath = " + test2log,
				"enabled = true" if 2 in enabled else "",
			)
			if unittest.F2B.log_level <= logging.DEBUG: # pragma: no cover
				_out_file(pjoin(cfg, "jail.conf"))

		# create default test actions:
		_write_action_cfg(actname="test-action1")
		_write_action_cfg(actname="test-action2")

		_write_jail_cfg(enabled=[1], actions=[1,2,3])
		# append one wrong configured jail:
		_write_file(pjoin(cfg, "jail.conf"), "a", "", "[broken-jail]", 
			"", "filter = broken-jail-filter", "enabled = true")

		_write_file(test1log, "w", *((str(int(MyTime.time())) + " failure 401 from 192.0.2.1: test 1",) * 3))
		_write_file(test2log, "w")
		_write_file(test3log, "w")
		
		# reload and wait for ban:
		self.pruneLog("[test-phase 1a]")
		if unittest.F2B.log_level < logging.DEBUG: # pragma: no cover
			_out_file(test1log)
		self.execCmd(SUCCESS, startparams, "reload")
		self.assertLogged(
			"Reload finished.",
			"1 ticket(s) in 'test-jail1", all=True, wait=MID_WAITTIME)
		self.assertLogged("Added logfile: %r" % test1log)
		self.assertLogged("[test-jail1] Ban 192.0.2.1")
		# test actions started:
		self.assertLogged(
			"stdout: '[test-jail1] test-action1: ** start'", 
			"stdout: '[test-jail1] test-action2: ** start'", all=True)
		# test restored is 0 (both actions available):
		self.assertLogged(
			"stdout: '[test-jail1] test-action2: ++ ban 192.0.2.1 restored: 0, err-code: 401'",
			"stdout: '[test-jail1] test-action3: ++ ban 192.0.2.1 restored: 0'",
			all=True, wait=MID_WAITTIME)

		# broken jail was logged (in client and server log):
		self.assertLogged(
			"Unable to read the filter 'broken-jail-filter'",
			"Errors in jail 'broken-jail'. Skipping...",
			"Jail 'broken-jail' skipped, because of wrong configuration", all=True)
		
		# enable both jails, 3 logs for jail1, etc...
		self.pruneLog("[test-phase 1b]")
		_write_jail_cfg(actions=[1,2])
		if unittest.F2B.log_level < logging.DEBUG: # pragma: no cover
			_out_file(test1log)
		self.execCmd(SUCCESS, startparams, "reload")
		self.assertLogged("Reload finished.", wait=MID_WAITTIME)
		# test not unbanned / banned again:
		self.assertNotLogged(
			"[test-jail1] Unban 192.0.2.1", 
			"[test-jail1] Ban 192.0.2.1", all=True)
		# test 2 new log files:
		self.assertLogged(
			"Added logfile: %r" % test2log, 
			"Added logfile: %r" % test3log, all=True)
		# test actions reloaded:
		self.assertLogged(
			"stdout: '[test-jail1] test-action1: .. reload'", 
			"stdout: '[test-jail1] test-action2: .. reload'", all=True)
		# test 1 new jail:
		self.assertLogged(
			"Creating new jail 'test-jail2'",
			"Jail 'test-jail2' started", all=True)
		# test action3 removed, test flushing successful (and no single unban occurred):
		self.assertLogged(
			"stdout: '[test-jail1] test-action3: -- flushing IPs'",
			"stdout: '[test-jail1] test-action3: __ stop'", all=True)
		self.assertNotLogged(
			"stdout: '[test-jail1] test-action3: -- unban 192.0.2.1'")
		
		# update action1, delete action2 (should be stopped via configuration)...
		self.pruneLog("[test-phase 2a]")
		_write_jail_cfg(actions=[1])
		_write_action_cfg(actname="test-action1", 
			start= "               echo '[<name>] %s: started.'" % "test-action1",
			reload="               echo '[<name>] %s: reloaded.'" % "test-action1", 
			stop=  "               echo '[<name>] %s: stopped.'" % "test-action1")
		self.execCmd(SUCCESS, startparams, "reload")
		self.assertLogged("Reload finished.", wait=MID_WAITTIME)
		# test not unbanned / banned again:
		self.assertNotLogged(
			"[test-jail1] Unban 192.0.2.1", 
			"[test-jail1] Ban 192.0.2.1", all=True)
		# no new log files:
		self.assertNotLogged("Added logfile:")
		# test action reloaded (update):
		self.assertLogged(
			"stdout: '[test-jail1] test-action1: .. reload'",
			"stdout: '[test-jail1] test-action1: reloaded.'", all=True)
		# test stopped action unbans:
		self.assertLogged(
			"stdout: '[test-jail1] test-action2: -- unban 192.0.2.1'")
		# test action stopped:
		self.assertLogged(
			"stdout: '[test-jail1] test-action2: __ stop'")
		self.assertNotLogged(
			"stdout: '[test-jail1] test-action1: -- unban 192.0.2.1'")
		
		# don't need action1 anymore:
		_write_action_cfg(actname="test-action1", allow=False)
		# leave action2 just to test restored interpolation:
		_write_jail_cfg(actions=[2,3])
		
		self.pruneLog("[test-phase 2b]")
		# write new failures:
		_write_file(test2log, "a+", *(
			(str(int(MyTime.time())) + "   error 403 from 192.0.2.2: test 2",) * 3 +
		  (str(int(MyTime.time())) + "   error 403 from 192.0.2.3: test 2",) * 3 +
		  (str(int(MyTime.time())) + " failure 401 from 192.0.2.4: test 2",) * 3 +
		  (str(int(MyTime.time())) + " failure 401 from 192.0.2.8: test 2",) * 3
		))
		if unittest.F2B.log_level < logging.DEBUG: # pragma: no cover
			_out_file(test2log)
		# test all will be found in jail1 and one in jail2:
		self.assertLogged(
			"2 ticket(s) in 'test-jail2",
			"5 ticket(s) in 'test-jail1", all=True, wait=MID_WAITTIME)
		# ban manually to cover restore in restart (phase 2c):
		self.execCmd(SUCCESS, startparams,
			"set", "test-jail2", "banip", "192.0.2.9")
		self.assertLogged(
			"3 ticket(s) in 'test-jail2", wait=MID_WAITTIME)
		self.assertLogged(
			"[test-jail1] Ban 192.0.2.2",
			"[test-jail1] Ban 192.0.2.3",
			"[test-jail1] Ban 192.0.2.4",
			"[test-jail1] Ban 192.0.2.8",
			"[test-jail2] Ban 192.0.2.4",
			"[test-jail2] Ban 192.0.2.8", 
			"[test-jail2] Ban 192.0.2.9", all=True)
		# test ips at all not visible for jail2:
		self.assertNotLogged(
			"[test-jail2] Found 192.0.2.2", 
			"[test-jail2] Ban 192.0.2.2",
			"[test-jail2] Found 192.0.2.3", 
			"[test-jail2] Ban 192.0.2.3", 
			all=True)
		# if observer available wait for it becomes idle (write all tickets to db):
		_observer_wait_idle()
		# test banned command:
		self.assertSortedEqual(self.execCmdDirect(startparams,
			'banned'), (0, [
				{'test-jail1': ['192.0.2.4', '192.0.2.1', '192.0.2.8', '192.0.2.3', '192.0.2.2']},
				{'test-jail2': ['192.0.2.4', '192.0.2.9', '192.0.2.8']}
			]
		))
		self.assertSortedEqual(self.execCmdDirect(startparams,
			'banned', '192.0.2.1', '192.0.2.4', '192.0.2.222'), (0, [
			  ['test-jail1'], ['test-jail1', 'test-jail2'], []
			]
		))
		self.assertSortedEqual(self.execCmdDirect(startparams,
			'get', 'test-jail1', 'banned')[1], [
				'192.0.2.4', '192.0.2.1', '192.0.2.8', '192.0.2.3', '192.0.2.2'])
		self.assertSortedEqual(self.execCmdDirect(startparams,
			'get', 'test-jail2', 'banned')[1], [
				'192.0.2.4', '192.0.2.9', '192.0.2.8'])
		self.assertEqual(self.execCmdDirect(startparams,
			'get', 'test-jail1', 'banned', '192.0.2.3')[1],  1)
		self.assertEqual(self.execCmdDirect(startparams,
			'get', 'test-jail1', 'banned', '192.0.2.9')[1],  0)
		self.assertEqual(self.execCmdDirect(startparams,
			'get', 'test-jail1', 'banned', '192.0.2.3', '192.0.2.9')[1],  [1, 0])

		# restart jail without unban all:
		self.pruneLog("[test-phase 2c]")
		self.execCmd(SUCCESS, startparams,
			"restart", "test-jail2")
		self.assertLogged(
			"Reload finished.",
			"Restore Ban",
			"3 ticket(s) in 'test-jail2", all=True, wait=MID_WAITTIME)
		# stop/start and unban/restore ban:
		self.assertLogged(
			"[test-jail2] Unban 192.0.2.4",
			"[test-jail2] Unban 192.0.2.8",
			"[test-jail2] Unban 192.0.2.9",
			"Jail 'test-jail2' stopped",
			"Jail 'test-jail2' started",
			"[test-jail2] Restore Ban 192.0.2.4",
			"[test-jail2] Restore Ban 192.0.2.8",
			"[test-jail2] Restore Ban 192.0.2.9", all=True
		)
		# test restored is 1 (only test-action2):
		self.assertLogged(
			"stdout: '[test-jail2] test-action2: ++ ban 192.0.2.4 restored: 1, err-code: 401'",
			"stdout: '[test-jail2] test-action2: ++ ban 192.0.2.8 restored: 1, err-code: 401'",
			all=True, wait=MID_WAITTIME)
		# test test-action3 not executed at all (norestored check):
		self.assertNotLogged(
			"stdout: '[test-jail2] test-action3: ++ ban 192.0.2.4 restored: 1'",
			"stdout: '[test-jail2] test-action3: ++ ban 192.0.2.8 restored: 1'",
			all=True)

		# ban manually to test later flush by unban all:
		self.pruneLog("[test-phase 2d]")
		self.execCmd(SUCCESS, startparams,
			"set", "test-jail2", "banip", "192.0.2.21")
		self.execCmd(SUCCESS, startparams,
			"set", "test-jail2", "banip", "192.0.2.22")
		self.assertLogged(
			"stdout: '[test-jail2] test-action3: ++ ban 192.0.2.22",
			"stdout: '[test-jail2] test-action3: ++ ban 192.0.2.22 ", all=True, wait=MID_WAITTIME)

		# get banned ips:
		_observer_wait_idle()
		self.pruneLog("[test-phase 2d.1]")
		self.execCmd(SUCCESS, startparams, "get", "test-jail2", "banip", "\n")
		self.assertLogged(
			"192.0.2.4", "192.0.2.8", "192.0.2.21", "192.0.2.22", all=True, wait=MID_WAITTIME)
		self.pruneLog("[test-phase 2d.2]")
		self.execCmd(SUCCESS, startparams, "get", "test-jail1", "banip")
		self.assertLogged(
			"192.0.2.1", "192.0.2.2", "192.0.2.3", "192.0.2.4", "192.0.2.8", all=True, wait=MID_WAITTIME)

		# restart jail with unban all:
		self.pruneLog("[test-phase 2e]")
		self.execCmd(SUCCESS, startparams,
			"restart", "--unban", "test-jail2")
		self.assertLogged(
			"Reload finished.",
			"Jail 'test-jail2' started", all=True, wait=MID_WAITTIME)
		self.assertLogged(
			"Jail 'test-jail2' stopped",
			"Jail 'test-jail2' started",
			"[test-jail2] Unban 192.0.2.4",
			"[test-jail2] Unban 192.0.2.8",
			"[test-jail2] Unban 192.0.2.9", all=True
		)
		# test unban (action2):
		self.assertLogged(
			"stdout: '[test-jail2] test-action2: -- unban 192.0.2.21",
			"stdout: '[test-jail2] test-action2: -- unban 192.0.2.22'", all=True)
		# test flush (action3, and no single unban via action3 occurred):
		self.assertLogged(
			"stdout: '[test-jail2] test-action3: -- flushing IPs'")
		self.assertNotLogged(
			"stdout: '[test-jail2] test-action3: -- unban 192.0.2.21'",
			"stdout: '[test-jail2] test-action3: -- unban 192.0.2.22'", all=True)
		# no more ban (unbanned all):
		self.assertNotLogged(
			"[test-jail2] Ban 192.0.2.4",
			"[test-jail2] Ban 192.0.2.8", all=True
		)

		# don't need actions anymore:
		_write_action_cfg(actname="test-action2", allow=False)
		_write_jail_cfg(actions=[])

		# reload jail1 without restart (without ban/unban):
		self.pruneLog("[test-phase 3]")
		self.execCmd(SUCCESS, startparams, "reload", "test-jail1")
		self.assertLogged("Reload finished.", wait=MID_WAITTIME)
		self.assertLogged(
			"Reload jail 'test-jail1'",
			"Jail 'test-jail1' reloaded", all=True)
		self.assertNotLogged(
			"Reload jail 'test-jail2'",
			"Jail 'test-jail2' reloaded",
			"Jail 'test-jail1' started", all=True
		)

		# whole reload, but this time with jail1 only (jail2 should be stopped via configuration):
		self.pruneLog("[test-phase 4]")
		_write_jail_cfg(enabled=[1])
		self.execCmd(SUCCESS, startparams, "reload")
		self.assertLogged("Reload finished.", wait=MID_WAITTIME)
		# test both jails should be reloaded:
		self.assertLogged(
			"Reload jail 'test-jail1'")
		# test jail2 goes down:
		self.assertLogged(
			"Stopping jail 'test-jail2'", 
			"Jail 'test-jail2' stopped", all=True)
		# test 2 log files removed:
		self.assertLogged(
			"Removed logfile: %r" % test2log, 
			"Removed logfile: %r" % test3log, all=True)

		# now write failures again and check already banned (jail1 was alive the whole time) and new bans occurred (jail1 was alive the whole time):
		self.pruneLog("[test-phase 5]")
		_write_file(test1log, "a+", *(
			(str(int(MyTime.time())) + " failure 401 from 192.0.2.1: test 5",) * 3 + 
			(str(int(MyTime.time())) + "   error 403 from 192.0.2.5: test 5",) * 3 +
			(str(int(MyTime.time())) + " failure 401 from 192.0.2.6: test 5",) * 3
		))
		if unittest.F2B.log_level < logging.DEBUG: # pragma: no cover
			_out_file(test1log)
		self.assertLogged(
			"6 ticket(s) in 'test-jail1",
			"[test-jail1] 192.0.2.1 already banned", all=True, wait=MID_WAITTIME)
		# test "failure" regexp still available:
		self.assertLogged(
			"[test-jail1] Found 192.0.2.1",
			"[test-jail1] Found 192.0.2.6",
			"[test-jail1] 192.0.2.1 already banned",
			"[test-jail1] Ban 192.0.2.6", all=True)
		# test "error" regexp no more available:
		self.assertNotLogged("[test-jail1] Found 192.0.2.5")

		# unban single ips:
		self.pruneLog("[test-phase 6a]")
		self.execCmd(SUCCESS, startparams,
			"--async", "unban", "192.0.2.5", "192.0.2.6")
		self.assertLogged(
			"192.0.2.5 is not banned",
			"[test-jail1] Unban 192.0.2.6", all=True, wait=MID_WAITTIME
		)
		# unban ips by subnet (cidr/mask):
		self.pruneLog("[test-phase 6b]")
		self.execCmd(SUCCESS, startparams,
			"--async", "unban", "192.0.2.2/31")
		self.assertLogged(
			"[test-jail1] Unban 192.0.2.2",
			"[test-jail1] Unban 192.0.2.3", all=True, wait=MID_WAITTIME
		)		
		self.execCmd(SUCCESS, startparams,
			"--async", "unban", "192.0.2.8/31", "192.0.2.100/31")
		self.assertLogged(
			"[test-jail1] Unban 192.0.2.8",
			"192.0.2.100/31 is not banned", all=True, wait=MID_WAITTIME)

		# ban/unban subnet(s):
		self.pruneLog("[test-phase 6c]")
		self.execCmd(SUCCESS, startparams,
			"--async", "set", "test-jail1", "banip", "192.0.2.96/28", "192.0.2.112/28")
		self.assertLogged(
			"[test-jail1] Ban 192.0.2.96/28",
			"[test-jail1] Ban 192.0.2.112/28", all=True, wait=MID_WAITTIME
		)
		self.execCmd(SUCCESS, startparams,
			"--async", "set", "test-jail1", "unbanip", "192.0.2.64/26"); # contains both subnets .96/28 and .112/28
		self.assertLogged(
			"[test-jail1] Unban 192.0.2.96/28",
			"[test-jail1] Unban 192.0.2.112/28", all=True, wait=MID_WAITTIME
		)

		# reload all (one jail) with unban all:
		self.pruneLog("[test-phase 7]")
		self.execCmd(SUCCESS, startparams,
			"reload", "--unban")
		self.assertLogged("Reload finished.", wait=MID_WAITTIME)
		# reloads unbanned all:
		self.assertLogged(
			"Jail 'test-jail1' reloaded",
			"[test-jail1] Unban 192.0.2.1",
			"[test-jail1] Unban 192.0.2.4", all=True
		)
		# no restart occurred, no more ban (unbanned all using option "--unban"):
		self.assertNotLogged(
			"Jail 'test-jail1' stopped",
			"Jail 'test-jail1' started",
			"[test-jail1] Ban 192.0.2.1",
			"[test-jail1] Ban 192.0.2.4", all=True
		)

		# unban all (just to test command, already empty - nothing to unban):
		self.pruneLog("[test-phase 7b]")
		self.execCmd(SUCCESS, startparams,
			"--async", "unban", "--all")
		self.assertLogged(
			"Flush ban list",
			"Unbanned 0, 0 ticket(s) in 'test-jail1'", all=True)

		# backend-switch (restart instead of reload):
		self.pruneLog("[test-phase 8a]")
		_write_jail_cfg(enabled=[1], backend="xxx-unknown-backend-zzz")
		self.execCmd(FAILED, startparams, "reload")
		self.assertLogged("Reload finished.", wait=MID_WAITTIME)
		self.assertLogged(
			"Restart jail 'test-jail1' (reason: 'polling' != ", 
			"Unknown backend ", all=True)

		self.pruneLog("[test-phase 8b]")
		_write_jail_cfg(enabled=[1])
		self.execCmd(SUCCESS, startparams, "reload")
		self.assertLogged("Reload finished.", wait=MID_WAITTIME)

		# several small cases (cover several parts):
		self.pruneLog("[test-phase end-1]")
		# wrong jail (not-started):
		self.execCmd(FAILED, startparams,
			"--async", "reload", "test-jail2")
		self.assertLogged("Reload finished.", wait=MID_WAITTIME)
		self.assertLogged("the jail 'test-jail2' does not exist")
		self.pruneLog()
		# unavailable jail (but exit 0), using --if-exists option:
		self.execCmd(SUCCESS, startparams,
			"--async", "reload", "--if-exists", "test-jail2")
		self.assertLogged("Reload finished.", wait=MID_WAITTIME)
		self.assertNotLogged(
			"Creating new jail 'test-jail2'",
			"Jail 'test-jail2' started", all=True)

		# restart all jails (without restart server):
		self.pruneLog("[test-phase end-2]")
		self.execCmd(SUCCESS, startparams,
			"--async", "reload", "--restart", "--all")
		self.assertLogged("Reload finished.", wait=MID_WAITTIME)
		self.assertLogged(
			"Jail 'test-jail1' stopped", 
			"Jail 'test-jail1' started", all=True, wait=MID_WAITTIME)

		# Coverage for pickle of IPAddr (as string):
		self.pruneLog("[test-phase end-3]")
		self.execCmd(SUCCESS, startparams,
			"--async", "set", "test-jail1", "addignoreip", "192.0.2.1/32", "2001:DB8::1/96")
		self.execCmd(SUCCESS, startparams,
			"--async", "get", "test-jail1", "ignoreip")
		self.assertLogged("192.0.2.1/32", "2001:DB8::1/96", all=True)

	# test action.d/nginx-block-map.conf --
	@unittest.F2B.skip_if_cfg_missing(action="nginx-block-map")
	@with_foreground_server_thread(startextra={
		# create log-file (avoid "not found" errors):
		'create_before_start': ('%(tmp)s/blck-failures.log',),
		# we need action.d/nginx-block-map.conf and blocklist_de:
		'use_stock_cfg': ('action.d',),
		# jail-config:
		'jails': (
			'[nginx-blck-lst]',
			'backend = polling',
			'usedns = no',
			'logpath = %(tmp)s/blck-failures.log',
			'action = nginx-block-map[srv_cmd="echo nginx", srv_pid="%(tmp)s/f2b.pid", blck_lst_file="%(tmp)s/blck-lst.map"]',
			'         blocklist_de[actionban=\'curl() { echo "*** curl" "$*";}; <Definition/actionban>\', email="Fail2Ban <fail2ban@localhost>", '
													  'apikey="TEST-API-KEY", agent="fail2ban-test-agent", service=<name>]',
			'filter =',
			'datepattern = ^Epoch',
			'failregex = ^ failure "<F-ID>[^"]+</F-ID>" - <ADDR>',
			'maxretry = 1', # ban by first failure
			'enabled = true',
	  )
	})
	def testServerActions_NginxBlockMap(self, tmp, startparams):
		cfg = pjoin(tmp, "config")
		lgfn = '%(tmp)s/blck-failures.log' % {'tmp': tmp}
		mpfn = '%(tmp)s/blck-lst.map' % {'tmp': tmp}
		# ban sessions (write log like nginx does it with f2b_session_errors log-format):
		_write_file(lgfn, "w+",
			str(int(MyTime.time())) + ' failure "125-000-001" - 192.0.2.1',
			str(int(MyTime.time())) + ' failure "125-000-002" - 192.0.2.1',
			str(int(MyTime.time())) + ' failure "125-000-003" - 192.0.2.1 (\xf2\xf0\xe5\xf2\xe8\xe9)',
			str(int(MyTime.time())) + ' failure "125-000-004" - 192.0.2.1 (\xf2\xf0\xe5\xf2\xe8\xe9)',
			str(int(MyTime.time())) + ' failure "125-000-005" - 192.0.2.1',
		)
		# check all sessions are banned (and blacklisted in map-file):
		self.assertLogged(
			"[nginx-blck-lst] Ban 125-000-001",
			"[nginx-blck-lst] Ban 125-000-002",
			"[nginx-blck-lst] Ban 125-000-003",
			"[nginx-blck-lst] Ban 125-000-004",
			"[nginx-blck-lst] Ban 125-000-005",
			"5 ticket(s)",
			all=True, wait=MID_WAITTIME
		)
		_out_file(mpfn)
		mp = _read_file(mpfn)
		self.assertIn('\\125-000-001 1;\n', mp)
		self.assertIn('\\125-000-002 1;\n', mp)
		self.assertIn('\\125-000-003 1;\n', mp)
		self.assertIn('\\125-000-004 1;\n', mp)
		self.assertIn('\\125-000-005 1;\n', mp)

		# check nginx reload is logged (pid of fail2ban is used to simulate success check nginx is running):
		self.assertLogged("stdout: 'nginx -qt'", "stdout: 'nginx -s reload'", all=True)
		# check blocklist_de substitution (e. g. new-line after <matches>):
		self.assertLogged(
			"stdout: '*** curl --fail --data-urlencode server=Fail2Ban <fail2ban@localhost>"
			                 " --data apikey=TEST-API-KEY --data service=nginx-blck-lst ",
			"stdout: ' --data format=text --user-agent fail2ban-test-agent",
			all=True, wait=MID_WAITTIME
		)

		# unban 1, 2 and 5:
		self.execCmd(SUCCESS, startparams, 'unban', '125-000-001', '125-000-002', '125-000-005')
		_out_file(mpfn)
		# check really unbanned but other sessions are still present (blacklisted in map-file):
		mp = _read_file(mpfn)
		self.assertNotIn('\\125-000-001 1;\n', mp)
		self.assertNotIn('\\125-000-002 1;\n', mp)
		self.assertNotIn('\\125-000-005 1;\n', mp)
		self.assertIn('\\125-000-003 1;\n', mp)
		self.assertIn('\\125-000-004 1;\n', mp)

		# stop server and wait for end:
		self.stopAndWaitForServerEnd(SUCCESS)

		# check flushed (all sessions were deleted from map-file):
		self.assertLogged("[nginx-blck-lst] Flush ticket(s) with nginx-block-map")
		_out_file(mpfn)
		mp = _read_file(mpfn)
		self.assertEqual(mp, '')

	@unittest.F2B.skip_if_cfg_missing(filter="sendmail-auth")
	@with_foreground_server_thread(startextra={
		# create log-file (avoid "not found" errors):
		'create_before_start': ('%(tmp)s/test.log',),
		'use_stock': True,
		# fail2ban.local:
		'f2b_local': (
			'[DEFAULT]',
			'dbmaxmatches = 1'
		),
		# jail.local config:
		'jails': (
			# default:
			'''test_action = dummy[actionstart_on_demand=1, init="start: %(__name__)s", target="%(tmp)s/test.txt",
      actionban='<known/actionban>; echo "found: <jail.found> / <jail.found_total>, banned: <jail.banned> / <jail.banned_total>"
        echo "<matches>"; printf "=====\\n%%b\\n=====\\n\\n" "<matches>" >> <target>',
      actionstop='<known/actionstop>; echo "stats <name> - found: <jail.found_total>, banned: <jail.banned_total>"']''',
			# jail sendmail-auth:
			'[sendmail-auth]',
			'backend = polling',
			'usedns = no',
			'logpath = %(tmp)s/test.log',
			'action = %(test_action)s',
			'filter = sendmail-auth[logtype=short]',
			'datepattern = ^Epoch',
			'maxretry = 3',
			'maxmatches = 2',
			'enabled = true',
			# jail sendmail-reject:
			'[sendmail-reject]',
			'backend = polling',
			'usedns = no',
			'logpath = %(tmp)s/test.log',
			'action = %(test_action)s',
			'filter = sendmail-reject[logtype=short]',
			'datepattern = ^Epoch',
			'maxretry = 3',
			'enabled = true',
		)
	})
	def testServerJails_Sendmail(self, tmp, startparams):
		cfg = pjoin(tmp, "config")
		lgfn = '%(tmp)s/test.log' % {'tmp': tmp}
		tofn = '%(tmp)s/test.txt' % {'tmp': tmp}

		smaut_msg = (
			str(int(MyTime.time())) + ' smtp1 sm-mta[5133]: s1000000000001: [192.0.2.1]: possible SMTP attack: command=AUTH, count=1',
			str(int(MyTime.time())) + ' smtp1 sm-mta[5133]: s1000000000002: [192.0.2.1]: possible SMTP attack: command=AUTH, count=2',
			str(int(MyTime.time())) + ' smtp1 sm-mta[5133]: s1000000000003: [192.0.2.1]: possible SMTP attack: command=AUTH, count=3',
		)
		smrej_msg = (
			str(int(MyTime.time())) + ' smtp1 sm-mta[21134]: s2000000000001: ruleset=check_rcpt, arg1=<123@example.com>, relay=xxx.dynamic.example.com [192.0.2.2], reject=550 5.7.1 <123@example.com>... Relaying denied. Proper authentication required.',
			str(int(MyTime.time())) + ' smtp1 sm-mta[21134]: s2000000000002: ruleset=check_rcpt, arg1=<345@example.com>, relay=xxx.dynamic.example.com [192.0.2.2], reject=550 5.7.1 <345@example.com>... Relaying denied. Proper authentication required.',
			str(int(MyTime.time())) + ' smtp1 sm-mta[21134]: s3000000000003: ruleset=check_rcpt, arg1=<567@example.com>, relay=xxx.dynamic.example.com [192.0.2.2], reject=550 5.7.1 <567@example.com>... Relaying denied. Proper authentication required.',
		)

		self.pruneLog("[test-phase sendmail-auth]")
		# write log:
		_write_file(lgfn, "w+", *smaut_msg)
		# wait and check it caused banned (and dump in the test-file):
		self.assertLogged(
			"[sendmail-auth] Ban 192.0.2.1",  "stdout: 'found: 0 / 3, banned: 1 / 1'",
			"1 ticket(s) in 'sendmail-auth'", all=True, wait=MID_WAITTIME)
		_out_file(tofn)
		td = _read_file(tofn)
		# check matches (maxmatches = 2, so only 2 & 3 available):
		m = smaut_msg[0]
		self.assertNotIn(m, td)
		for m in smaut_msg[1:]:
			self.assertIn(m, td)

		self.pruneLog("[test-phase sendmail-reject]")
		# write log:
		_write_file(lgfn, "a+", *smrej_msg)
		# wait and check it caused banned (and dump in the test-file):
		self.assertLogged(
			"[sendmail-reject] Ban 192.0.2.2", "stdout: 'found: 0 / 3, banned: 1 / 1'",
			"1 ticket(s) in 'sendmail-reject'", all=True, wait=MID_WAITTIME)
		_out_file(tofn)
		td = _read_file(tofn)
		# check matches (no maxmatches, so all matched messages are available):
		for m in smrej_msg:
			self.assertIn(m, td)

		self.pruneLog("[test-phase restart sendmail-*]")
		# restart jails (active ban-tickets should be restored):
		self.execCmd(SUCCESS, startparams,
			"reload", "--restart", "--all")
		# wait a bit:
		self.assertLogged(
			"Reload finished.",
			"stdout: 'stats sendmail-auth - found: 3, banned: 1'",
			"stdout: 'stats sendmail-reject - found: 3, banned: 1'",
			"[sendmail-auth] Restore Ban 192.0.2.1", "1 ticket(s) in 'sendmail-auth'", all=True, wait=MID_WAITTIME)
		# check matches again - (dbmaxmatches = 1), so it should be only last match after restart:
		td = _read_file(tofn)
		m = smaut_msg[-1]
		self.assertLogged(m)
		self.assertIn(m, td)
		for m in smaut_msg[0:-1]:
			self.assertNotLogged(m)
			self.assertNotIn(m, td)
		# wait for restore of reject-jail:
		self.assertLogged(
			"[sendmail-reject] Restore Ban 192.0.2.2", "1 ticket(s) in 'sendmail-reject'", all=True, wait=MID_WAITTIME)
		td = _read_file(tofn)
		m = smrej_msg[-1]
		self.assertLogged(m)
		self.assertIn(m, td)
		for m in smrej_msg[0:-1]:
			self.assertNotLogged(m)
			self.assertNotIn(m, td)

		self.pruneLog("[test-phase stop server]")
		# stop server and wait for end:
		self.stopAndWaitForServerEnd(SUCCESS)

		# just to debug actionstop:
		self.assertFalse(exists(tofn))

	@with_foreground_server_thread()
	def testServerObserver(self, tmp, startparams):
		cfg = pjoin(tmp, "config")
		test1log = pjoin(tmp, "test1.log")

		os.mkdir(pjoin(cfg, "action.d"))
		def _write_action_cfg(actname="test-action1", prolong=True):
			fn = pjoin(cfg, "action.d", "%s.conf" % actname)
			_write_file(fn, "w",
				"[DEFAULT]",
				"",
				"[Definition]",
				"actionban =     printf %%s \"[%(name)s] %(actname)s: ++ ban <ip> -c <bancount> -t <bantime> : <F-MSG>\"", \
				"actionprolong = printf %%s \"[%(name)s] %(actname)s: ++ prolong <ip> -c <bancount> -t <bantime> : <F-MSG>\"" \
					if prolong else "",
				"actionunban =   printf %%b '[%(name)s] %(actname)s: -- unban <ip>'",
			)
			if unittest.F2B.log_level <= logging.DEBUG: # pragma: no cover
				_out_file(fn)

		def _write_jail_cfg(backend="polling"):
			_write_file(pjoin(cfg, "jail.conf"), "w",
				"[INCLUDES]", "",
				"[DEFAULT]", "",
				"usedns = no",
				"maxretry = 3",
				"findtime = 1m",
				"bantime = 5m",
				"bantime.increment = true",
				"datepattern = {^LN-BEG}EPOCH",
				"",
				"[test-jail1]", "backend = " + backend, "filter =", 
				"action = test-action1[name='%(__name__)s']",
				"         test-action2[name='%(__name__)s']",
				"logpath = " + test1log,
				r"failregex = ^\s*failure <F-ERRCODE>401|403</F-ERRCODE> from <HOST>:\s*<F-MSG>.*</F-MSG>$",
				"enabled = true",
				"",
			)
			if unittest.F2B.log_level <= logging.DEBUG: # pragma: no cover
				_out_file(pjoin(cfg, "jail.conf"))

		# create test config:
		_write_action_cfg(actname="test-action1", prolong=False)
		_write_action_cfg(actname="test-action2", prolong=True)
		_write_jail_cfg()

		_write_file(test1log, "w")
		# initial start:
		self.pruneLog("[test-phase 0) time-0]")
		self.execCmd(SUCCESS, startparams, "reload")
		# generate bad ip:
		_write_file(test1log, "w+", *(
		  (str(int(MyTime.time())) + " failure 401 from 192.0.2.11: I'm bad \"hacker\" `` $(echo test)",) * 3
		))
		# wait for ban:
		_observer_wait_idle()
		self.assertLogged(
			"stdout: '[test-jail1] test-action1: ++ ban 192.0.2.11 -c 1 -t 300 : ",
			"stdout: '[test-jail1] test-action2: ++ ban 192.0.2.11 -c 1 -t 300 : ",
			all=True, wait=MID_WAITTIME)
		# wait for observer idle (write all tickets to db):
		_observer_wait_idle()

		self.pruneLog("[test-phase 1) time+10m]")
		# jump to the future (+10 minutes):
		_time_shift(10)
		_observer_wait_idle()
		self.assertLogged(
			"stdout: '[test-jail1] test-action1: -- unban 192.0.2.11",
			"stdout: '[test-jail1] test-action2: -- unban 192.0.2.11",
			"0 ticket(s) in 'test-jail1'",
			all=True, wait=MID_WAITTIME)
		_observer_wait_idle()

		self.pruneLog("[test-phase 2) time+10m]")
		# following tests are time-related - observer can prolong ticket (increase ban-time) 
		# before banning, so block it here before banFound called, prolong case later:
		wakeObs = False
		_observer_wait_before_incrban(lambda: wakeObs)
		# write again (IP already bad):
		_write_file(test1log, "a+", *(
		  (str(int(MyTime.time())) + " failure 401 from 192.0.2.11: I'm very bad \"hacker\" `` $(echo test)",) * 2
		))
		# wait for ban:
		self.assertLogged(
			"stdout: '[test-jail1] test-action1: ++ ban 192.0.2.11 -c 2 -t 300 : ",
			"stdout: '[test-jail1] test-action2: ++ ban 192.0.2.11 -c 2 -t 300 : ",
			all=True, wait=MID_WAITTIME)
		# get banned ips with time:
		self.pruneLog("[test-phase 2) time+10m - get-ips]")
		self.execCmd(SUCCESS, startparams, "get", "test-jail1", "banip", "--with-time")
		self.assertLogged(
			"192.0.2.11", "+ 300 =", all=True, wait=MID_WAITTIME)
		# unblock observer here and wait it is done:
		wakeObs = True
		_observer_wait_idle()

		self.pruneLog("[test-phase 2) time+11m]")
		# jump to the future (+1 minute):
		_time_shift(1)
		# wait for observer idle (write all tickets to db):
		_observer_wait_idle()
		# wait for prolong:
		self.assertLogged(
			"stdout: '[test-jail1] test-action2: ++ prolong 192.0.2.11 -c 2 -t 600 : ",
			all=True, wait=MID_WAITTIME)

		# get banned ips with time:
		_observer_wait_idle()
		self.pruneLog("[test-phase 2) time+11m - get-ips]")
		self.execCmd(SUCCESS, startparams, "get", "test-jail1", "banip", "--with-time")
		self.assertLogged(
			"192.0.2.11", "+ 600 =", all=True, wait=MID_WAITTIME)

		# test stop with busy observer:
		self.pruneLog("[test-phase end) stop on busy observer]")
		tearDownMyTime()
		a = {'state': 0}
		obsMain = Observers.Main
		def _long_action():
			logSys.info('++ observer enters busy state ...')
			a['state'] = 1
			Utils.wait_for(lambda: a['state'] == 2, MAX_WAITTIME)
			obsMain.db_purge(); # does nothing (db is already None)
			logSys.info('-- observer leaves busy state.')
		obsMain.add('call', _long_action)
		obsMain.add('call', lambda: None)
		# wait observer enter busy state:
		Utils.wait_for(lambda: a['state'] == 1, MAX_WAITTIME)
		# overwrite default wait time (normally 5 seconds):
		obsMain_stop = obsMain.stop
		def _stop(wtime=(0.01 if unittest.F2B.fast else 0.1), forceQuit=True):
			return obsMain_stop(wtime, forceQuit)
		obsMain.stop = _stop
		# stop server and wait for end:
		self.stopAndWaitForServerEnd(SUCCESS)
		# check observer and db state:
		self.assertNotLogged('observer leaves busy state')
		self.assertFalse(obsMain.idle)
		self.assertEqual(obsMain._ObserverThread__db, None)
		# server is exited without wait for observer, stop it now:
		a['state'] = 2
		self.assertLogged('observer leaves busy state', wait=True)
		obsMain.join()

	# test multiple start/stop of the server (threaded in foreground) --
	if False: # pragma: no cover
		@with_foreground_server_thread()
		def _testServerStartStop(self, tmp, startparams):
			# stop server and wait for end:
			self.stopAndWaitForServerEnd(SUCCESS)

		def testServerStartStop(self):
			for i in xrange(2000):
				self._testServerStartStop()