Skip to content

Commit dacd15e

Browse files
committed
Test for internal checks
Fix pylint/pycodestyle
1 parent 4037247 commit dacd15e

27 files changed

+561
-123
lines changed

.pylintrc

+4-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,10 @@ disable=print-statement,
132132
no-member,
133133
fixme,
134134
invalid-name,
135-
access-member-before-definition
135+
access-member-before-definition,
136+
useless-object-inheritance,
137+
consider-using-dict-comprehension,
138+
consider-using-set-comprehension
136139

137140
# Enable the message, report, category or checker with the given id(s). You can
138141
# either give multiple identifier separated by comma (,) or put this option

alignak/action.py

-7
Original file line numberDiff line numberDiff line change
@@ -551,13 +551,6 @@ def _execute(self, force_shell=sys.version_info < (2, 7)):
551551
# 2.7 and higher Python version need a list of arguments for the started command
552552
cmd = self.command
553553
if not force_shell:
554-
# todo: perharps necessary, to be investigated!
555-
# try:
556-
# self.command = self.command.encode('utf8')
557-
# except Exception as exp:
558-
# print(exp)
559-
# pass
560-
561554
try:
562555
cmd = shlex.split(self.command)
563556
except Exception as exp: # pylint: disable=broad-except

alignak/brok.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
from datetime import datetime
5353

5454
from alignak.alignakobject import get_a_new_object_id
55-
from alignak.misc.serialization import serialize, unserialize, AlignakClassLookupException
55+
from alignak.misc.serialization import serialize, unserialize
5656

5757

5858
class Brok(object):
@@ -149,10 +149,7 @@ def prepare(self):
149149
# Maybe the Brok is a old daemon one or was already prepared
150150
# if so, the data is already ok
151151
if hasattr(self, 'prepared') and not self.prepared:
152-
try:
153-
self.data = unserialize(self.data)
154-
except AlignakClassLookupException: # pragma: no cover, should never happen...
155-
raise
152+
self.data = unserialize(self.data)
156153
if self.instance_id:
157154
self.data['instance_id'] = self.instance_id
158155
self.prepared = True

alignak/complexexpression.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ def eval_cor_pattern(self, pattern): # pylint:disable=R0912
186186
tmp = ''
187187
stacked_par = 0
188188
for char in pattern:
189-
if char == ',' or char == '|':
189+
if char in (',', '|'):
190190
# Maybe we are in a par, if so, just stack it
191191
if in_par:
192192
tmp += char
@@ -199,7 +199,7 @@ def eval_cor_pattern(self, pattern): # pylint:disable=R0912
199199
node.sons.append(son)
200200
tmp = ''
201201

202-
elif char == '&' or char == '+':
202+
elif char in ('&', '+'):
203203
# Maybe we are in a par, if so, just stack it
204204
if in_par:
205205
tmp += char
@@ -298,7 +298,6 @@ def find_object(self, pattern):
298298
elts.remove('*')
299299
return elts, error
300300

301-
else: # templates
302-
obj = self.grps.find_hosts_that_use_template(pattern)
301+
obj = self.grps.find_hosts_that_use_template(pattern)
303302

304303
return obj, error

alignak/daemon.py

-1
Original file line numberDiff line numberDiff line change
@@ -985,7 +985,6 @@ def do_before_loop(self): # pylint: disable=no-self-use
985985
:return: None
986986
"""
987987
logger.debug("Nothing to do before the main loop")
988-
return
989988

990989
def do_main_loop(self):
991990
# pylint: disable=too-many-branches, too-many-statements, too-many-locals

alignak/daemons/arbiterdaemon.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1881,7 +1881,7 @@ def get_livesynthesis(self):
18811881
return res
18821882

18831883
def get_alignak_status(self, details=False):
1884-
# pylint: disable=too-many-locals
1884+
# pylint: disable=too-many-locals, too-many-branches
18851885
"""Push the alignak overall state as a passive check
18861886
18871887
Build all the daemons overall state as a passive check that can be notified

alignak/daemons/brokerdaemon.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -423,11 +423,11 @@ def do_loop_turn(self):
423423
logger.info("No initial broks were raised, "
424424
"my scheduler is not yet ready...")
425425
return
426-
else:
427-
self.got_initial_broks = True
428-
logger.debug("Got %d initial broks from '%s'",
429-
my_initial_broks, satellite.name)
430-
statsmgr.gauge('broks.initial.%s.count' % satellite.name, my_initial_broks)
426+
427+
self.got_initial_broks = True
428+
logger.debug("Got %d initial broks from '%s'",
429+
my_initial_broks, satellite.name)
430+
statsmgr.gauge('broks.initial.%s.count' % satellite.name, my_initial_broks)
431431
except LinkError as exp:
432432
logger.warning("Scheduler connection failed, I could not get initial broks!")
433433

alignak/external_command.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -3032,7 +3032,7 @@ def process_host_check_result(self, host, status_code, plugin_output):
30323032
plugin_output)
30333033
return
30343034

3035-
chk = host.launch_check(int(now), self.hosts, self.services, self.timeperiods,
3035+
chk = host.launch_check(now, self.hosts, self.services, self.timeperiods,
30363036
self.daemon.macromodulations, self.daemon.checkmodulations,
30373037
self.daemon.checks, force=True)
30383038
# We will not have a check if an host/service is checked but it has no defined check_command
@@ -3519,7 +3519,7 @@ def schedule_host_downtime(self, host, start_time, end_time, fixed,
35193519
host.add_downtime(downtime)
35203520

35213521
self.daemon.get_and_register_status_brok(host)
3522-
if trigger_id != '' and trigger_id != 0:
3522+
if trigger_id not in ('', 0):
35233523
for item in self.daemon.hosts:
35243524
if trigger_id in item.downtimes:
35253525
host.downtimes[trigger_id].trigger_me(downtime.uuid)
@@ -3682,7 +3682,7 @@ def schedule_svc_downtime(self, service, start_time, end_time, fixed,
36823682
downtime.add_automatic_comment(service)
36833683
service.add_downtime(downtime)
36843684
self.daemon.get_and_register_status_brok(service)
3685-
if trigger_id != '' and trigger_id != 0:
3685+
if trigger_id not in ('', 0):
36863686
for item in self.daemon.services:
36873687
if trigger_id in item.downtimes:
36883688
service.downtimes[trigger_id].trigger_me(downtime.uuid)

alignak/http/arbiter_interface.py

-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
from alignak.http.generic_interface import GenericInterface
2727
from alignak.util import split_semicolon
2828
from alignak.external_command import ExternalCommand
29-
from alignak.misc.serialization import serialize, unserialize
3029

3130
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
3231

@@ -431,7 +430,6 @@ def monitoring_problems(self):
431430
res = self.get_id()
432431
res['problems'] = {}
433432
for scheduler_link in self.app.conf.schedulers:
434-
print("Scheduler link: %s" % scheduler_link)
435433
sched_res = scheduler_link.con.get('monitoring_problems', wait=True)
436434
res['problems'][scheduler_link.name] = {}
437435
if '_freshness' in sched_res:

alignak/misc/common.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,14 @@
4949
try:
5050
from setproctitle import setproctitle # pylint: disable=unused-import
5151
except ImportError as err: # pragma: no cover, setproctitle is in the requirements.txt
52-
def setproctitle(title): # pylint: disable=unused-argument
52+
def setproctitle(title): # pylint: disable=unused-argument, useless-return
5353
"""
5454
Return name
5555
:param title: name of process
5656
:type title: str
5757
:return: None
5858
"""
59+
# Do nothing...
5960
return None
6061

6162
# Friendly names for the system signals

alignak/misc/serialization.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def unserialize(j_obj, no_load=False):
112112
data_dict[key] = unserialize(value, True)
113113
return data_dict
114114

115-
elif isinstance(data, list):
115+
if isinstance(data, list):
116116
return [unserialize(item, True) for item in data]
117117

118118
return data

alignak/objects/host.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -560,11 +560,11 @@ def is_state(self, status):
560560
if status == self.state:
561561
return True
562562
# Now low status
563-
elif status == 'o' and self.state == u'UP':
563+
if status == 'o' and self.state == u'UP':
564564
return True
565-
elif status == 'd' and self.state == u'DOWN':
565+
if status == 'd' and self.state == u'DOWN':
566566
return True
567-
elif status in ['u', 'x'] and self.state == u'UNREACHABLE':
567+
if status in ['u', 'x'] and self.state == u'UNREACHABLE':
568568
return True
569569
return False
570570

alignak/objects/item.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -864,7 +864,7 @@ def manage_conflict(self, item, name):
864864
if existing_prio < item_prio:
865865
# Existing item has lower priority, so it has precedence.
866866
return existing
867-
elif existing_prio > item_prio:
867+
if existing_prio > item_prio:
868868
# New item has lower priority, so it has precedence.
869869
# Existing item will be deleted below
870870
pass

alignak/objects/realm.py

-3
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,6 @@ def set_level(self, level, realms):
300300
301301
:return: None
302302
"""
303-
# print("- set: %s (%s)" % (self.get_name(), self.uuid))
304303
self.level = level
305304
self.all_sub_members = []
306305
self.all_sub_members_names = []
@@ -318,8 +317,6 @@ def set_level(self, level, realms):
318317
grand_child = realms.find_by_name(grand_child)
319318
if grand_child:
320319
self.all_sub_members.append(grand_child.uuid)
321-
# print("-> : %s" % self.all_sub_members)
322-
# print("-> : %s" % self.all_sub_members_names)
323320
return self.all_sub_members_names
324321

325322
def get_all_subs_satellites_by_type(self, sat_type, realms):

alignak/objects/schedulingitem.py

+49-39
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@
6666
import re
6767
import random
6868
import time
69-
import datetime
69+
from datetime import datetime
7070
import traceback
7171
import logging
7272

@@ -1167,7 +1167,7 @@ def schedule(self, hosts, services, timeperiods, macromodulations, checkmodulati
11671167
:type force_time: None | int
11681168
:return: None
11691169
"""
1170-
# next_chk il already set, do not change
1170+
# next_chk is already set, do not change
11711171
# unless we force the check or the time
11721172
if self.in_checking and not (force or force_time):
11731173
return None
@@ -1185,8 +1185,8 @@ def schedule(self, hosts, services, timeperiods, macromodulations, checkmodulati
11851185
if self.check_interval == 0 and not force:
11861186
if cls.my_type == 'service':
11871187
return None
1188-
else: # host
1189-
self.check_interval = 300 / cls.interval_length
1188+
1189+
self.check_interval = 300 / cls.interval_length
11901190

11911191
# Interval change is in a HARD state or not
11921192
# If the retry is 0, take the normal value
@@ -1252,8 +1252,13 @@ def schedule(self, hosts, services, timeperiods, macromodulations, checkmodulati
12521252

12531253
logger.debug("-> schedule: %s / %s (interval: %d, added: %d)",
12541254
self.get_full_name(),
1255-
datetime.datetime.fromtimestamp(self.next_chk).strftime('%Y-%m-%d %H:%M:%S'),
1255+
datetime.utcfromtimestamp(self.next_chk).strftime('%Y-%m-%d %H:%M:%S'),
12561256
interval, time_add)
1257+
if os.getenv('ALIGNAK_LOG_CHECKS', None):
1258+
logger.info("--ALC-- -> next check for %s at %s (interval: %d, added: %d)",
1259+
self.get_full_name(),
1260+
datetime.utcfromtimestamp(self.next_chk).strftime('%Y-%m-%d %H:%M:%S'),
1261+
interval, time_add)
12571262
# Get the command to launch, and put it in queue
12581263
return self.launch_check(self.next_chk, hosts, services, timeperiods, macromodulations,
12591264
checkmodulations, checks, force=force)
@@ -1586,27 +1591,10 @@ def consume_result(self, chk, notification_period, hosts,
15861591
logger.info("Got check result: %d for %s",
15871592
chk.exit_status, self.get_full_name())
15881593

1589-
# # Protect against bad type output
1590-
# try:
1591-
# # if str, convert to unicode
1592-
# if isinstance(chk.output, str):
1593-
# chk.output = chk.output.decode('utf8', 'ignore')
1594-
# chk.long_output = chk.long_output.decode('utf8', 'ignore')
1595-
# except AttributeError:
1596-
# # Python 3 raises an exception!
1597-
# pass
1598-
#
1599-
# try:
1600-
# if isinstance(chk.perf_data, str):
1601-
# chk.perf_data = chk.perf_data.decode('utf8', 'ignore')
1602-
# except AttributeError:
1603-
# # Python 3 raises an exception!
1604-
# pass
1605-
16061594
if os.getenv('ALIGNAK_LOG_CHECKS', None):
16071595
level = ['info', 'warning', 'error', 'critical'][min(chk.exit_status, 3)]
16081596
func = getattr(logger, level)
1609-
func("Check result for '%s', exit: %d, output: %s",
1597+
func("--ALC-- check result for %s, exit: %d, output: %s",
16101598
self.get_full_name(), chk.exit_status, chk.output)
16111599

16121600
# ============ MANAGE THE CHECK ============ #
@@ -1928,7 +1916,7 @@ def update_event_and_problem_id(self):
19281916
SchedulingItem.current_problem_id += 1
19291917
self.last_problem_id = self.current_problem_id
19301918
self.current_problem_id = SchedulingItem.current_problem_id
1931-
elif self.state != ok_up and self.last_state != ok_up:
1919+
elif ok_up not in (self.state, self.last_state):
19321920
# State transitions between non-OK states
19331921
# (e.g. WARNING to CRITICAL) do not cause
19341922
# this problem id to increase.
@@ -2718,6 +2706,9 @@ def manage_internal_check(self, hosts, services, check, hostgroups, servicegroup
27182706
:return: None
27192707
"""
27202708
logger.debug("Internal check: %s - %s", self.get_full_name(), check.command)
2709+
if os.getenv('ALIGNAK_LOG_CHECKS', None):
2710+
logger.info("--ALC-- Internal check: %s - %s", self.get_full_name(), check.command)
2711+
# Business rule
27212712
if check.command.startswith('bp_'):
27222713
try:
27232714
# Re evaluate the business rule to take into account macro
@@ -2744,6 +2735,7 @@ def manage_internal_check(self, hosts, services, check, hostgroups, servicegroup
27442735
logger.debug("[%s] Error while re-evaluating business rule:\n%s",
27452736
self.get_name(), traceback.format_exc())
27462737
state = 3
2738+
27472739
# _internal_host_up is for putting host as UP
27482740
elif check.command == '_internal_host_up':
27492741
state = 0
@@ -2777,14 +2769,21 @@ def manage_internal_check(self, hosts, services, check, hostgroups, servicegroup
27772769
state = 3
27782770
check.output = u'Malformed host internal check'
27792771
else:
2780-
state = 3
2772+
state = check_result[1].strip()
2773+
# If multiple possible states - choose a random one
2774+
if ',' in check_result[1]:
2775+
states = check_result[1].split(',')
2776+
state = states[random.randint(0, len(states) - 1)]
2777+
27812778
try:
2782-
state = int(check_result[1])
2779+
state = int(state)
27832780
except ValueError:
27842781
pass
27852782
check.output = u'Host internal check result: %d' % state
2786-
if len(check_result) > 2:
2783+
if len(check_result) > 2 and check_result[2]:
27872784
check.output = check_result[2]
2785+
if '%d' in check.output:
2786+
check.output = check.output % state
27882787

27892788
check.execution_time = 0
27902789
if 'ALIGNAK_LOG_ACTIONS' in os.environ:
@@ -2804,14 +2803,25 @@ def manage_internal_check(self, hosts, services, check, hostgroups, servicegroup
28042803
state = 3
28052804
check.output = u'Malformed service internal check'
28062805
else:
2807-
state = 3
2806+
state = check_result[1].strip()
2807+
# If multiple possible states - choose a random one
2808+
if ',' in check_result[1]:
2809+
states = check_result[1].split(',')
2810+
state = states[random.randint(0, len(states) - 1)]
2811+
2812+
# In SOFT state type, do not change current state - let the new state go to HARD
2813+
if self.state_type == 'SOFT':
2814+
state = self.state_id
2815+
28082816
try:
2809-
state = int(check_result[1])
2817+
state = int(state)
28102818
except ValueError:
28112819
pass
28122820
check.output = u'Service internal check result: %d' % state
2813-
if len(check_result) > 1:
2814-
check.output = check_result[1]
2821+
if len(check_result) > 2 and check_result[2]:
2822+
check.output = check_result[2]
2823+
if '%d' in check.output:
2824+
check.output = check.output % state
28152825

28162826
check.execution_time = 0
28172827
if 'ALIGNAK_LOG_ACTIONS' in os.environ:
@@ -3105,14 +3115,14 @@ def unset_impact_state(self):
31053115
self.state = self.state_before_impact
31063116
self.state_id = self.state_id_before_impact
31073117

3108-
def last_time_non_ok_or_up(self): # pragma: no cover, base function
3109-
"""Get the last time the item was in a non-OK state
3110-
3111-
:return: return 0
3112-
:rtype: int
3113-
"""
3114-
pass
3115-
3118+
# def last_time_non_ok_or_up(self): # pragma: no cover, base function
3119+
# """Get the last time the item was in a non-OK state
3120+
#
3121+
# :return: return 0
3122+
# :rtype: int
3123+
# """
3124+
# pass
3125+
#
31163126
def set_unreachable(self):
31173127
"""Set unreachable: all our parents (dependencies) are not ok
31183128
Unreachable is different from down/critical

0 commit comments

Comments
 (0)