id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,300
|
test_bad_service_interval.py
|
shinken-solutions_shinken/test/test_bad_service_interval.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Sebastien Coavoux, s.coavoux@free.fr
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestBadServiceInterval(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_bad_service_interval.cfg')
def test_bad_conf(self):
self.assertFalse(self.conf.conf_is_correct)
self.assert_any_log_match("services conf incorrect!!")
self.assert_any_log_match(r"Error while pythonizing parameter 'check_interval': (could not convert string to float: '1,555'|invalid literal for float\(\): 1,555)")
if __name__ == '__main__':
unittest.main()
| 1,561
|
Python
|
.py
| 35
| 42.085714
| 171
| 0.743573
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,301
|
test_hostgroup_no_host.py
|
shinken-solutions_shinken/test/test_hostgroup_no_host.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestHostGroupNoHost(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_hostgroup_no_host.cfg')
def test_hostgroup_wit_no_host(self):
self.assertTrue(self.sched.conf.conf_is_correct)
if __name__ == '__main__':
unittest.main()
| 1,272
|
Python
|
.py
| 31
| 38.83871
| 82
| 0.756494
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,302
|
test_startmember_group.py
|
shinken-solutions_shinken/test/test_startmember_group.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestStarMemberGroup(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_startmember_group.cfg')
# Check if service apply on a hostgroup * is good or not
def test_starmembergroupdef(self):
hg = self.sched.conf.hostgroups.find_by_name('ping-servers')
self.assertIsNot(hg, None)
print(hg.members)
h = self.sched.conf.hosts.find_by_name('test_host_0')
r = self.sched.conf.hosts.find_by_name('test_router_0')
self.assertIn(h, hg.members)
self.assertIn(r, hg.members)
s = self.sched.conf.services.find_srv_by_name_and_hostname('test_host_0', 'PING')
self.assertIsNot(s, None)
if __name__ == '__main__':
unittest.main()
| 1,727
|
Python
|
.py
| 40
| 39.55
| 89
| 0.725268
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,303
|
test_properties_defaults.py
|
shinken-solutions_shinken/test/test_properties_defaults.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012:
# Hartmut Goebel <h.goebel@crazy-compilers.com>
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
"""
Test default values for item types.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import __import_shinken
from shinken.property import UnusedProp, none_object
import shinken.daemon
# TODO: clean import *
from shinken_test import *
from shinken.property import *
class PropertiesTester(object):
def test_unused_properties(self):
item = self.item # shortcut
for name in self.unused_props:
self.assertIn(name, item.properties,
msg='property %r not found in %s' % (name, self.item.my_type))
self.assertIsInstance(item.properties[name], UnusedProp)
def test_properties_without_default(self):
item = self.item # shortcut
for name in self.without_default:
self.assertIn(name, item.properties,
msg='property %r not found in %s' % (name, self.item.my_type))
self.assertIsInstance(
item.properties[name],
( ListProp, StringProp, IntegerProp ),
msg='property %r is not `ListProp` or `StringProp` but %r' % (name, item.properties[name])
)
self.assertTrue(item.properties[name].required)
def test_default_values(self):
item = self.item # shortcut
for name, value in self.properties.items():
self.assertIn(name, item.properties,
msg='property %r not found in %s' % (name, self.item.my_type))
if hasattr(item.properties[name], 'default'):
if item.properties[name].default != value:
print("%s, %s: %s, %s" % (name, value, item.properties[name].default, value))
self.assertEqual(item.properties[name].default, value)
def test_all_props_are_tested(self):
item = self.item # shortcut
prop_names = set(list(self.properties.keys()) + self.unused_props + self.without_default)
for name in item.properties:
if name.startswith('$') and name.endswith('$'):
continue
self.assertIn(name, prop_names,
msg='unknown property %r found' % name)
class TestConfig(PropertiesTester, ShinkenTest):
unused_props = [
'log_file', 'object_cache_file', 'precached_object_file',
'temp_file', 'status_file', 'status_update_interval',
'command_check_interval', 'external_command_buffer_slots',
'check_for_updates', 'bare_update_checks',
'retain_state_information', 'use_retained_program_state',
'use_retained_scheduling_info',
'retained_host_attribute_mask',
'retained_service_attribute_mask',
'retained_process_host_attribute_mask',
'retained_process_service_attribute_mask',
'retained_contact_host_attribute_mask',
'retained_contact_service_attribute_mask', 'sleep_time',
'service_inter_check_delay_method',
'service_interleave_factor', 'max_concurrent_checks',
'check_result_reaper_frequency',
'max_check_result_reaper_time', 'check_result_path',
'max_check_result_file_age', 'host_inter_check_delay_method',
'free_child_process_memory', 'child_processes_fork_twice',
'admin_email', 'admin_pager', 'event_broker_options',
'debug_file', 'debug_level', 'debug_verbosity',
'max_debug_file_size']
without_default = []
properties = dict([
('prefix', '/usr/local/shinken/'),
('workdir', '/var/run/shinken/'),
('config_base_dir', ''),
('modules_dir', '/var/lib/shinken/modules'),
('use_local_log', True),
('log_level', 'WARNING'),
('local_log', '/var/log/shinken/arbiterd.log'),
('resource_file', '/tmp/resources.txt'),
('shinken_user', shinken.daemon.get_cur_user()),
('shinken_group', shinken.daemon.get_cur_group()),
('enable_notifications', True),
('execute_service_checks', True),
('accept_passive_service_checks', True),
('execute_host_checks', True),
('accept_passive_host_checks', True),
('enable_event_handlers', True),
('log_rotation_method', 'd'),
('log_archive_path', '/usr/local/shinken/var/archives'),
('check_external_commands', True),
('command_file', ''),
('lock_file', '/var/run/shinken/arbiterd.pid'),
('state_retention_file', ''),
('retention_update_interval', 60),
('use_syslog', False),
('log_notifications', True),
('log_service_retries', True),
('log_host_retries', True),
('log_event_handlers', True),
('log_initial_states', True),
('log_external_commands', True),
('log_passive_checks', True),
('global_host_event_handler', ''),
('global_service_event_handler', ''),
('max_service_check_spread', 30),
('max_host_check_spread', 30),
('interval_length', 60),
('auto_reschedule_checks', True),
('auto_rescheduling_interval', 1),
('auto_rescheduling_window', 180),
('use_aggressive_host_checking', False),
('translate_passive_host_checks', True),
('passive_host_checks_are_soft', True),
('enable_predictive_host_dependency_checks', True),
('enable_predictive_service_dependency_checks', True),
('cached_host_check_horizon', 0),
('cached_service_check_horizon', 0),
('use_large_installation_tweaks', '0'),
('enable_environment_macros', True),
('enable_flap_detection', True),
('low_service_flap_threshold', 20),
('high_service_flap_threshold', 30),
('low_host_flap_threshold', 20),
('high_host_flap_threshold', 30),
('soft_state_dependencies', False),
('service_check_timeout', 60),
('host_check_timeout', 30),
('event_handler_timeout', 30),
('notification_timeout', 30),
('ocsp_timeout', 15),
('ochp_timeout', 15),
('perfdata_timeout', 5),
('obsess_over_services', False),
('ocsp_command', ''),
('obsess_over_hosts', False),
('ochp_command', ''),
('process_performance_data', True),
('host_perfdata_command', ''),
('service_perfdata_command', ''),
('host_perfdata_file', ''),
('service_perfdata_file', ''),
('host_perfdata_file_template', '/tmp/host.perf'),
('service_perfdata_file_template', '/tmp/host.perf'),
('host_perfdata_file_mode', 'a'),
('service_perfdata_file_mode', 'a'),
('host_perfdata_file_processing_interval', 15),
('service_perfdata_file_processing_interval', 15),
('host_perfdata_file_processing_command', ''),
('service_perfdata_file_processing_command', None),
('check_for_orphaned_services', True),
('check_for_orphaned_hosts', True),
('check_service_freshness', True),
('service_freshness_check_interval', 60),
('check_host_freshness', True),
('host_freshness_check_interval', 60),
('additional_freshness_latency', 15),
('enable_embedded_perl', True),
('use_embedded_perl_implicitly', False),
('date_format', None),
('use_timezone', ''),
('illegal_object_name_chars', '`~!$%^&*"|\'<>?,()='),
('illegal_macro_output_chars', ''),
('use_regexp_matching', False),
('use_true_regexp_matching', None),
('broker_module', ''),
('modified_attributes', 0),
('daemon_enabled', True),
('graceful_enabled', False),
('aggressive_memory_management', False),
('conflict_policy', 'loose'),
# Shinken specific
('idontcareaboutsecurity', False),
('flap_history', 20),
('max_plugins_output_length', 8192),
('no_event_handlers_during_downtimes', False),
('cleaning_queues_interval', 900),
('disable_old_nagios_parameters_whining', False),
('enable_problem_impacts_states_change', False),
('enable_problem_impacts_states_reprocessing', False),
('resource_macros_names', []),
# SSL part
('use_ssl', False),
('server_key', 'etc/certs/server.key'),
('ca_cert', 'etc/certs/ca.pem'),
('server_cert', 'etc/certs/server.cert'),
('hard_ssl_name_check', False),
('http_backend', 'auto'),
('human_timestamp_log', False),
# Discovery part
('strip_idname_fqdn', True),
('runners_timeout', 3600),
('pack_distribution_file', 'pack_distribution.dat'),
# WebUI part
('webui_lock_file', 'webui.pid'),
('webui_port', 8080),
('webui_host', '0.0.0.0'),
('use_multiprocesses_serializer', False),
('daemon_thread_pool_size', 16),
('enable_environment_macros', True),
('timeout_exit_status', 2),
# kernel.shinken.io part
('api_key', ''),
('secret', ''),
('http_proxy', ''),
# statsd part
('statsd_host', 'localhost'),
('statsd_port', 8125),
('statsd_prefix', 'shinken'),
('statsd_enabled', False),
('statsd_interval', 5),
('statsd_types', None),
('statsd_pattern', None),
])
def setUp(self):
from shinken.objects.config import Config
self.item = Config()
class TestCommand(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['command_name', 'command_line']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('poller_tag', 'None'),
('reactionner_tag', 'None'),
('module_type', None),
('timeout', -1),
('enable_environment_macros', False),
('priority', 100),
])
def setUp(self):
from shinken.objects.command import Command
self.item = Command()
class TestContactgroup(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['contactgroup_name', 'contactgroup_members', 'alias']
properties = dict([
('members', None),
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('unknown_members', None),
('id', 0),
])
def setUp(self):
from shinken.objects.contactgroup import Contactgroup
self.item = Contactgroup()
class TestContact(PropertiesTester, ShinkenTest):
unused_props = []
without_default = [
'contact_name',
'host_notification_period', 'service_notification_period',
'host_notification_commands', 'service_notification_commands'
]
properties = dict([
('service_notification_options', ['']),
('host_notification_options', ['']),
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('alias', 'none'),
('contactgroups', []),
('host_notifications_enabled', True),
('service_notifications_enabled', True),
('min_business_impact', 0),
('email', 'none'),
('pager', 'none'),
('address1', 'none'),
('address2', 'none'),
('address3', 'none'),
('address4', 'none'),
('address5', 'none'),
('address6', 'none'),
('can_submit_commands', False),
('is_admin', False),
('expert', False),
('retain_status_information', True),
('notificationways', []),
('password', 'NOPASSWORDSET'),
])
def setUp(self):
from shinken.objects.contact import Contact
self.item = Contact()
class TestDiscoveryrule(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['discoveryrule_name']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('creation_type', 'service'),
('discoveryrule_order', 0),
])
def setUp(self):
from shinken.objects.discoveryrule import Discoveryrule
self.item = Discoveryrule()
class TestDiscoveryrun(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['discoveryrun_name', 'discoveryrun_command']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
])
def setUp(self):
from shinken.objects.discoveryrun import Discoveryrun
self.item = Discoveryrun()
class TestEscalation(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['escalation_name', 'first_notification', 'last_notification', 'first_notification_time', 'last_notification_time']
properties = dict([
('contact_groups', []),
('contacts', []),
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('notification_interval', -1),
('escalation_period', ''),
('escalation_options', ['d','u','r','w','c']),
])
def setUp(self):
from shinken.objects.escalation import Escalation
self.item = Escalation()
class TestHostdependency(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['dependent_host_name', 'host_name']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('dependent_hostgroup_name', ''),
('hostgroup_name', ''),
('inherits_parent', False),
('execution_failure_criteria', ['n']),
('notification_failure_criteria', ['n']),
('dependency_period', ''),
])
def setUp(self):
from shinken.objects.hostdependency import Hostdependency
self.item = Hostdependency()
class TestHostescalation(PropertiesTester, ShinkenTest):
unused_props = []
without_default = [
'host_name', 'hostgroup_name',
'first_notification', 'last_notification',
'contacts', 'contact_groups',
'first_notification_time', 'last_notification_time',
]
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('notification_interval', 30),
('escalation_period', ''),
('escalation_options', ['d','u','r','w','c']),
])
def setUp(self):
from shinken.objects.hostescalation import Hostescalation
self.item = Hostescalation()
class TestHostextinfo(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['host_name']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('notes', ''),
('notes_url', ''),
('icon_image', ''),
('icon_image_alt', ''),
('vrml_image', ''),
('statusmap_image', ''),
('2d_coords', ''),
('3d_coords', ''),
])
def setUp(self):
from shinken.objects.hostextinfo import HostExtInfo
self.item = HostExtInfo()
class TestHostgroup(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['hostgroup_name', 'hostgroup_members', 'alias']
properties = dict([
('members', None),
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('unknown_members', None),
('id', 0),
('notes', ''),
('notes_url', ''),
('action_url', ''),
('realm', ''),
])
def setUp(self):
from shinken.objects.hostgroup import Hostgroup
self.item = Hostgroup()
class TestHost(PropertiesTester, ShinkenTest):
unused_props = []
without_default = [
'host_name', 'alias', 'address',
'check_period', 'notification_period']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('display_name', ''),
('parents', []),
('hostgroups', []),
('check_command', '_internal_host_up'),
('initial_state', ''),
('initial_output', ''),
('check_interval', 0),
('max_check_attempts', 1),
('retry_interval', 0),
('active_checks_enabled', True),
('passive_checks_enabled', True),
('obsess_over_host', False),
('check_freshness', False),
('freshness_threshold', 0),
('event_handler', ''),
('event_handler_enabled', False),
('low_flap_threshold', 25),
('high_flap_threshold', 50),
('flap_detection_enabled', True),
('flap_detection_options', ['o','d','u']),
('process_perf_data', True),
('retain_status_information', True),
('retain_nonstatus_information', True),
('contacts', []),
('contact_groups', []),
('notification_interval', 60),
('first_notification_delay', 0),
('notification_options', ['d','u','r','f']),
('notifications_enabled', True),
('stalking_options', ['']),
('notes', ''),
('notes_url', ''),
('action_url', ''),
('icon_image', ''),
('icon_image_alt', ''),
('icon_set', ''),
('vrml_image', ''),
('statusmap_image', ''),
('2d_coords', ''),
('3d_coords', ''),
('failure_prediction_enabled', False),
('realm', None),
('poller_tag', 'None'),
('reactionner_tag', 'None'),
('resultmodulations', []),
('business_impact_modulations', []),
('escalations', []),
('business_impact', 2),
('trigger', ''),
('trigger_name', ''),
('trigger_broker_raise_enabled', False),
('time_to_orphanage', 300),
('trending_policies', []),
('checkmodulations', []),
('macromodulations', []),
('custom_views', []),
('service_overrides', []),
('service_excludes', []),
('service_includes', []),
('business_rule_output_template', ''),
('business_rule_smart_notifications', False),
('business_rule_downtime_as_ack', False),
('labels', []),
('snapshot_interval', 5),
('snapshot_command', ''),
('snapshot_enabled', False),
('snapshot_period', ''),
('snapshot_criteria', ['d','u']),
('business_rule_host_notification_options', []),
('business_rule_service_notification_options', []),
('maintenance_period', ''),
('maintenance_checks_enabled', False),
('maintenance_check_command', ''),
('maintenance_check_period', ''),
('maintenance_check_interval', 0),
('maintenance_retry_interval', 0),
('priority', 100),
])
def setUp(self):
from shinken.objects.host import Host
self.item = Host()
class TestModule(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['module_name', 'module_type']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('modules', ['']),
])
def setUp(self):
from shinken.objects.module import Module
self.item = Module()
class TestNotificationway(PropertiesTester, ShinkenTest):
unused_props = []
without_default = [
'notificationway_name',
'host_notification_period', 'service_notification_period',
'host_notification_commands', 'service_notification_commands']
properties = dict([
('service_notification_options', ['']),
('host_notification_options', ['']),
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('host_notifications_enabled', True),
('service_notifications_enabled', True),
('min_business_impact', 0),
])
def setUp(self):
from shinken.objects.notificationway import NotificationWay
self.item = NotificationWay()
class TestPack(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['pack_name']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
])
def setUp(self):
from shinken.objects.pack import Pack
self.item = Pack()
class TestRealm(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['realm_name']
properties = dict([
('members', None),
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('unknown_members', None),
('id', 0),
('realm_members', []),
('higher_realms', []),
('default', False),
('broker_complete_links', False),
])
def setUp(self):
from shinken.objects.realm import Realm
self.item = Realm()
class TestResultmodulation(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['resultmodulation_name']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('exit_codes_match', []),
('exit_code_modulation', None),
('modulation_period', None),
])
def setUp(self):
from shinken.objects.resultmodulation import Resultmodulation
self.item = Resultmodulation()
class TestServicedependency(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['dependent_host_name', 'dependent_service_description', 'host_name', 'service_description']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('dependent_hostgroup_name', ''),
('hostgroup_name', ''),
('inherits_parent', False),
('execution_failure_criteria', ['n']),
('notification_failure_criteria', ['n']),
('dependency_period', ''),
('explode_hostgroup', False),
])
def setUp(self):
from shinken.objects.servicedependency import Servicedependency
self.item = Servicedependency()
class TestServiceescalation(PropertiesTester, ShinkenTest):
unused_props = []
without_default = [
'host_name', 'hostgroup_name',
'service_description',
'first_notification', 'last_notification',
'contacts', 'contact_groups',
'first_notification_time', 'last_notification_time']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('notification_interval', 30),
('escalation_period', ''),
('escalation_options', ['d','u','r','w','c']),
])
def setUp(self):
from shinken.objects.serviceescalation import Serviceescalation
self.item = Serviceescalation()
class TestServiceextinfo(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['host_name', 'service_description']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('notes', ''),
('notes_url', ''),
('icon_image', ''),
('icon_image_alt', ''),
])
def setUp(self):
from shinken.objects.serviceextinfo import ServiceExtInfo
self.item = ServiceExtInfo()
class TestServicegroup(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['servicegroup_name', 'servicegroup_members', 'alias']
properties = dict([
('members', None),
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('unknown_members', None),
('id', 0),
('notes', ''),
('notes_url', ''),
('action_url', ''),
])
def setUp(self):
from shinken.objects.servicegroup import Servicegroup
self.item = Servicegroup()
class TestService(PropertiesTester, ShinkenTest):
unused_props = []
without_default = [
'host_name', 'service_description',
'check_command', 'check_interval',
'retry_interval', 'check_period', 'notification_period']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('max_check_attempts', 1),
('hostgroup_name', ''),
('display_name', ''),
('servicegroups', []),
('is_volatile', False),
('initial_state', ''),
('initial_output', ''),
('active_checks_enabled', True),
('passive_checks_enabled', True),
('obsess_over_service', False),
('check_freshness', False),
('freshness_threshold', 0),
('event_handler', ''),
('event_handler_enabled', False),
('low_flap_threshold', -1),
('high_flap_threshold', -1),
('flap_detection_enabled', True),
('flap_detection_options', ['o','w','c','u']),
('process_perf_data', True),
('retain_status_information', True),
('retain_nonstatus_information', True),
('notification_interval', 60),
('first_notification_delay', 0),
('notification_options', ['w','u','c','r','f','s']),
('notifications_enabled', True),
('contacts', []),
('contact_groups', []),
('stalking_options', ['']),
('notes', ''),
('notes_url', ''),
('action_url', ''),
('icon_image', ''),
('icon_image_alt', ''),
('icon_set', ''),
('failure_prediction_enabled', False),
('parallelize_check', True),
('poller_tag', 'None'),
('reactionner_tag', 'None'),
('resultmodulations', []),
('business_impact_modulations', []),
('escalations', []),
('duplicate_foreach', ''),
('default_value', ''),
('business_impact', 2),
('trigger', ''),
('trigger_name', ''),
('trigger_broker_raise_enabled', False),
('time_to_orphanage', 300),
('trending_policies', []),
('checkmodulations', []),
('macromodulations', []),
('aggregation', ''),
('service_dependencies', None),
('custom_views', []),
('merge_host_contacts', False),
('business_rule_output_template', ''),
('business_rule_smart_notifications', False),
('business_rule_downtime_as_ack', False),
('labels', []),
('snapshot_interval', 5),
('snapshot_command', ''),
('snapshot_enabled', False),
('snapshot_period', ''),
('snapshot_criteria', ['w','c','u']),
('business_rule_host_notification_options', []),
('business_rule_service_notification_options', []),
('host_dependency_enabled', True),
('maintenance_period', ''),
('maintenance_checks_enabled', False),
('maintenance_check_command', ''),
('maintenance_check_period', ''),
('maintenance_check_interval', 0),
('maintenance_retry_interval', 0),
('priority', 100),
])
def setUp(self):
from shinken.objects.service import Service
self.item = Service()
class TestTimeperiod(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['timeperiod_name']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('definition_order', 100),
('name', ''),
('alias', ''),
('register', True),
('dateranges', []),
('exclude', []),
('is_active', False),
])
def setUp(self):
from shinken.objects.timeperiod import Timeperiod
self.item = Timeperiod()
class TestTrigger(PropertiesTester, ShinkenTest):
unused_props = []
without_default = ['trigger_name']
properties = dict([
('imported_from', 'unknown'),
('use', None),
('register', True),
('definition_order', 100),
('name', ''),
('code_src', ''),
])
def setUp(self):
from shinken.objects.trigger import Trigger
self.item = Trigger()
if __name__ == '__main__':
unittest.main()
| 30,153
|
Python
|
.py
| 811
| 28.817509
| 137
| 0.562836
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,304
|
test_on_demand_event_handlers.py
|
shinken-solutions_shinken/test/test_on_demand_event_handlers.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test acknowledge of problems
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_on_demand_event_handlers.cfg')
def test_on_demand_eh(self):
self.print_header()
# retry_interval 2
# critical notification
# run loop -> another notification
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.assertEqual(False, svc.event_handler_enabled)
self.scheduler_loop(5, [[svc, 2, 'CRITICAL']])
# We should NOT see any event hnalder here :)
self.assert_no_log_match('SERVICE EVENT HANDLER')
print("MY Actions", self.sched.actions)
# And now we ask for a launch in manual
now = time.time()
cmd = "[%lu] LAUNCH_SVC_EVENT_HANDLER;test_host_0;test_ok_0" % now
self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.worker_loop()
self.assert_any_log_match('SERVICE EVENT HANDLER')
if __name__ == '__main__':
unittest.main()
| 2,475
|
Python
|
.py
| 56
| 38.892857
| 91
| 0.648379
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,305
|
test_obsess.py
|
shinken-solutions_shinken/test/test_obsess.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test acknowledge of problems
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_obsess.cfg')
def test_ocsp(self):
self.print_header()
# retry_interval 2
# critical notification
# run loop -> another notification
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.assertTrue(svc.obsess_over_service)
self.assertTrue(svc.__class__.obsess_over)
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(1, self.count_actions())
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(1, self.count_actions())
now = time.time()
cmd = "[%lu] STOP_OBSESSING_OVER_SVC;test_host_0;test_ok_0" % now
self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.worker_loop()
self.assertFalse(svc.obsess_over_service)
self.assertTrue(svc.__class__.obsess_over)
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(0, self.count_actions())
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(0, self.count_actions())
now = time.time()
cmd = "[%lu] START_OBSESSING_OVER_SVC;test_host_0;test_ok_0" % now
self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.worker_loop()
self.assertTrue(svc.obsess_over_service)
self.assertTrue(svc.__class__.obsess_over)
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(1, self.count_actions())
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(1, self.count_actions())
now = time.time()
cmd = "[%lu] START_OBSESSING_OVER_SVC_CHECKS" % now
self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.worker_loop()
self.assertTrue(svc.obsess_over_service)
self.assertTrue(svc.__class__.obsess_over)
now = time.time()
cmd = "[%lu] STOP_OBSESSING_OVER_SVC_CHECKS" % now
self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.worker_loop()
self.assertTrue(svc.obsess_over_service)
self.assertFalse(svc.__class__.obsess_over)
def test_ochp(self):
self.print_header()
# retry_interval 2
# critical notification
# run loop -> another notification
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'OK']])
self.show_actions()
self.assertEqual(1, self.count_actions())
self.scheduler_loop(1, [[router, 0, 'OK']])
self.show_actions()
print("host", host.obsess_over)
print("rout", router.obsess_over)
print("host", host.obsess_over_host)
print("rout", router.obsess_over_host)
self.assertEqual(0, self.count_actions())
self.assertTrue(host.obsess_over_host)
self.assertFalse(router.obsess_over_host)
# the router does not obsess (host definition)
# but it's class does (shinken.cfg)
self.assertTrue(router.__class__.obsess_over)
if __name__ == '__main__':
unittest.main()
| 5,208
|
Python
|
.py
| 118
| 36.915254
| 91
| 0.608747
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,306
|
test_unknown_do_not_change.py
|
shinken-solutions_shinken/test/test_unknown_do_not_change.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestUnknownNotChangeState(ShinkenTest):
# Uncomment this is you want to use a specific configuration
# for your test
#def setUp(self):
# self.setup_with_file('etc/shinken_1r_1h_1s.cfg')
# We got problem with unknown results on bad connections
# for critical services and host: if it was in a notification pass
# then the notification is restarted, but it's just a missing data,
# not a reason to warn about it
def test_unknown_do_not_change_state(self):
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
print("GO OK" * 10)
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [router, 0, 'UP | rtt=10'], [svc, 0, 'OK | value1=0 value2=0']])
self.assertEqual('OK', svc.state)
self.assertEqual('HARD', svc.state_type)
print("GO CRITICAL SOFT" * 10)
# Ok we are UP, now we seach to go in trouble
self.scheduler_loop(1, [[svc, 2, 'PROBLEM | value1=1 value2=2']])
# CRITICAL/SOFT
self.assertEqual('CRITICAL', svc.state)
self.assertEqual('SOFT', svc.state_type)
# And again and again :)
print("GO CRITICAL HARD" * 10)
self.scheduler_loop(2, [[svc, 2, 'PROBLEM | value1=1 value2=2']])
# CRITICAL/HARD
self.assertEqual('CRITICAL', svc.state)
self.assertEqual('HARD', svc.state_type)
# Should have a notification about it
self.assert_any_log_match('SERVICE NOTIFICATION.*;CRITICAL')
self.show_and_clear_logs()
print("GO UNKNOWN HARD" * 10)
# Then we make it as a unknown state
self.scheduler_loop(1, [[svc, 3, 'Unknown | value1=1 value2=2']])
# And we DO NOT WANT A NOTIF HERE
self.assert_no_log_match('SERVICE NOTIFICATION.*;UNKNOWN')
self.show_and_clear_logs()
print("Return CRITICAL HARD" * 10)
# Then we came back as CRITICAL
self.scheduler_loop(1, [[svc, 2, 'CRITICAL | value1=1 value2=2']])
print(svc.state, svc.state_type)
self.assert_no_log_match('SERVICE NOTIFICATION.*;CRITICAL')
self.show_and_clear_logs()
print("Still CRITICAL HARD" * 10)
# Then we came back as CRITICAL
self.scheduler_loop(1, [[svc, 2, 'CRITICAL | value1=1 value2=2']])
print(svc.state, svc.state_type)
self.assert_no_log_match('SERVICE NOTIFICATION.*;CRITICAL')
self.show_and_clear_logs()
# We check if we can still have new notifications of course
# And we speedup the notification
for n in svc.notifications_in_progress.values():
n.t_to_go = time.time()
self.scheduler_loop(1, [[svc, 2, 'CRITICAL | value1=1 value2=2']])
print(svc.state, svc.state_type)
self.assert_any_log_match('SERVICE NOTIFICATION.*;CRITICAL')
self.show_and_clear_logs()
# We got problem with unknown results on bad connections
# for critical services and host: if it was in a notification pass
# then the notification is restarted, but it's just a missing data,
# not a reason to warn about it
def test_unknown_do_not_change_state_with_different_exit_status_phase(self):
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
print("GO OK" * 10)
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [router, 0, 'UP | rtt=10'], [svc, 0, 'OK | value1=0 value2=0']])
self.assertEqual('OK', svc.state)
self.assertEqual('HARD', svc.state_type)
print("GO CRITICAL SOFT" * 10)
# Ok we are UP, now we seach to go in trouble
self.scheduler_loop(1, [[svc, 2, 'PROBLEM | value1=1 value2=2']])
# CRITICAL/SOFT
self.assertEqual('CRITICAL', svc.state)
self.assertEqual('SOFT', svc.state_type)
# And again and again :)
print("GO CRITICAL HARD" * 10)
self.scheduler_loop(2, [[svc, 2, 'PROBLEM | value1=1 value2=2']])
# CRITICAL/HARD
self.assertEqual('CRITICAL', svc.state)
self.assertEqual('HARD', svc.state_type)
# Should have a notification about it
self.assert_any_log_match('SERVICE NOTIFICATION.*;CRITICAL')
self.show_and_clear_logs()
print("GO UNKNOWN HARD" * 10)
# Then we make it as a unknown state
self.scheduler_loop(1, [[svc, 3, 'Unknown | value1=1 value2=2']])
# And we DO NOT WANT A NOTIF HERE
self.assert_no_log_match('SERVICE NOTIFICATION.*;UNKNOWN')
self.show_and_clear_logs()
print("Return CRITICAL HARD" * 10)
# Then we came back as WARNING here, so a different than we came in the phase!
self.scheduler_loop(1, [[svc, 1, 'WARNING | value1=1 value2=2']])
print(svc.state, svc.state_type)
self.assert_any_log_match('SERVICE NOTIFICATION.*;WARNING')
self.show_and_clear_logs()
# We check if we can still have new notifications of course
# And we speedup the notification
for n in svc.notifications_in_progress.values():
n.t_to_go = time.time()
self.scheduler_loop(1, [[svc, 1, 'WARNING | value1=1 value2=2']])
print(svc.state, svc.state_type)
self.assert_any_log_match('SERVICE NOTIFICATION.*;WARNING')
self.show_and_clear_logs()
# And what if we came back as critical so? :)
self.scheduler_loop(1, [[svc, 2, 'CRITICAL | value1=1 value2=2']])
print(svc.state, svc.state_type)
self.assert_any_log_match('SERVICE NOTIFICATION.*;CRITICAL')
self.show_and_clear_logs()
# But we want to still raise notif as unknown if we first met this state
def test_unknown_still_raise_notif(self):
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [router, 0, 'UP | rtt=10'], [svc, 0, 'OK | value1=0 value2=0']])
self.assertEqual('OK', svc.state)
self.assertEqual('HARD', svc.state_type)
# Ok we are UP, now we seach to go in trouble
self.scheduler_loop(1, [[svc, 3, 'PROBLEM | value1=1 value2=2']])
# UNKOWN/SOFT
self.assertEqual('UNKNOWN', svc.state)
self.assertEqual('SOFT', svc.state_type)
# And again and again :)
self.scheduler_loop(2, [[svc, 3, 'PROBLEM | value1=1 value2=2']])
# UNKNOWN/HARD
self.assertEqual('UNKNOWN', svc.state)
self.assertEqual('HARD', svc.state_type)
# Should have a notification about it!
self.assert_any_log_match('SERVICE NOTIFICATION.*;UNKNOWN')
self.show_and_clear_logs()
# Then we make it as a critical state
# and we want a notif too
self.scheduler_loop(1, [[svc, 2, 'critical | value1=1 value2=2']])
self.assert_any_log_match('SERVICE NOTIFICATION.*;CRITICAL')
self.show_and_clear_logs()
# We got problem with unknown results on bad connections
# for critical services and host: if it was in a notification pass
# then the notification is restarted, but it's just a missing data,
# not a reason to warn about it
def test_unreach_do_not_change_state(self):
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
print("GO OK" * 10)
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [router, 0, 'UP | rtt=10'], [svc, 0, 'OK | value1=0 value2=0']])
self.assertEqual('OK', svc.state)
self.assertEqual('HARD', svc.state_type)
print("GO DOWN SOFT" * 10)
# Ok we are UP, now we seach to go in trouble
self.scheduler_loop(1, [[host, 2, 'PROBLEM | value1=1 value2=2']])
# CRITICAL/SOFT
self.assertEqual('DOWN', host.state)
self.assertEqual('SOFT', host.state_type)
# And again and again :)
print("GO CRITICAL HARD" * 10)
self.scheduler_loop(2, [[host, 2, 'PROBLEM | value1=1 value2=2']])
# CRITICAL/HARD
self.assertEqual('DOWN', host.state)
self.assertEqual('HARD', host.state_type)
# Should have a notification about it
self.assert_any_log_match('HOST NOTIFICATION.*;DOWN')
self.show_and_clear_logs()
print("GO UNREACH HARD" * 10)
# Then we make it as a unknown state
self.scheduler_loop(3, [[router, 2, 'Bad router | value1=1 value2=2']])
# so we warn about the router, not the host
self.assert_any_log_match('HOST NOTIFICATION.*;DOWN')
self.show_and_clear_logs()
print("BIBI" * 100)
for n in host.notifications_in_progress.values():
print(n.__dict__)
# the we go in UNREACH
self.scheduler_loop(1, [[host, 2, 'CRITICAL | value1=1 value2=2']])
print(host.state, host.state_type)
self.show_and_clear_logs()
self.assertEqual('UNREACHABLE', host.state)
self.assertEqual('HARD', host.state_type)
# The the router came back :)
print("Router is back from Hell" * 10)
self.scheduler_loop(1, [[router, 0, 'Ok, I am back guys | value1=1 value2=2']])
self.assert_any_log_match('HOST NOTIFICATION.*;UP')
self.show_and_clear_logs()
# But how the host will say now?
self.scheduler_loop(1, [[host, 2, 'CRITICAL | value1=1 value2=2']])
print(host.state, host.state_type)
# And here we DO NOT WANT new notification
# If you follow, it THE important point of this test!
self.assert_no_log_match('HOST NOTIFICATION.*;DOWN')
self.show_and_clear_logs()
print("Now go in the future, I want a notification")
# Check if we still got the next notification for this of course
# Hack so the notification will raise now if it can
for n in host.notifications_in_progress.values():
n.t_to_go = time.time()
self.scheduler_loop(1, [[host, 2, 'CRITICAL | value1=1 value2=2']])
print(host.state, host.state_type)
# And here we DO NOT WANT new notification
self.assert_any_log_match('HOST NOTIFICATION.*;DOWN')
self.show_and_clear_logs()
if __name__ == '__main__':
unittest.main()
| 12,785
|
Python
|
.py
| 248
| 43.504032
| 133
| 0.637557
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,307
|
test_module_on_module.py
|
shinken-solutions_shinken/test/test_module_on_module.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestModuleOnModule(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_module_on_module.cfg')
def test_module_on_module(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
mod1 = self.sched.conf.modules.find_by_name("Simple-log")
self.assertIsNot(mod1, None)
print("Got module", mod1.get_name())
mod_sub = self.sched.conf.modules.find_by_name("ToNdodb_Mysql")
self.assertIsNot(mod_sub, None)
print("Got sub module", mod_sub.get_name())
self.assertIn(mod_sub, mod1.modules)
self.assertEqual([], mod_sub.modules)
if __name__ == '__main__':
unittest.main()
| 1,800
|
Python
|
.py
| 44
| 36.704545
| 82
| 0.709216
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,308
|
test_no_check_period.py
|
shinken-solutions_shinken/test/test_no_check_period.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestNoCheckPeriod(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_no_check_period.cfg')
def test_no_check_period(self):
self.assertTrue(self.conf.conf_is_correct)
if __name__ == '__main__':
unittest.main()
| 1,256
|
Python
|
.py
| 31
| 38.322581
| 82
| 0.754934
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,309
|
test_hostdep_with_multiple_names.py
|
shinken-solutions_shinken/test/test_hostdep_with_multiple_names.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestHostDepWithMultipleNames(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_hostdep_with_multiple_names.cfg')
def test_DepWithMultipleNames(self):
for n in ['svn1', 'svn2', 'svn3', 'svn4', 'nas1', 'nas2', 'nas3']:
val = globals()[n] = self.sched.hosts.find_by_name(n)
self.assertIsNot(val, None)
# We check that nas3 is a father of svn4, the simple case
self.assertIn(nas3, [e[0] for e in svn4.act_depend_of])
# Now the more complex one
for son in [svn1, svn2, svn3]:
for father in [nas1, nas2]:
print('Checking if', father.get_name(), 'is the father of', son.get_name())
print(son.act_depend_of)
for e in son.act_depend_of:
print(e[0].get_name())
self.assertIn(father, [e[0] for e in son.act_depend_of])
if __name__ == '__main__':
unittest.main()
| 1,951
|
Python
|
.py
| 43
| 39.976744
| 91
| 0.678778
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,310
|
test_nullinheritance.py
|
shinken-solutions_shinken/test/test_nullinheritance.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestNullInheritance(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_nullinheritance.cfg')
# We search to see if null as value really delete the inheritance
# of a property
def test_null_inheritance(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
self.assertEqual('', svc.icon_image)
if __name__ == '__main__':
unittest.main()
| 1,434
|
Python
|
.py
| 34
| 39.647059
| 91
| 0.746408
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,311
|
test_dependencies.py
|
shinken-solutions_shinken/test/test_dependencies.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test host- and service-downtimes.
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_dependencies.cfg')
def test_service_dependencies(self):
self.print_header()
now = time.time()
test_host_0 = self.sched.hosts.find_by_name("test_host_0")
test_host_1 = self.sched.hosts.find_by_name("test_host_1")
test_host_0.checks_in_progress = []
test_host_1.checks_in_progress = []
test_host_0.act_depend_of = [] # ignore the router
test_host_1.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore other routers
test_host_0_test_ok_0 = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
test_host_0_test_ok_1 = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_1")
test_host_1_test_ok_0 = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "test_ok_0")
test_host_1_test_ok_1 = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "test_ok_1")
# the most important: test_ok_0 is in the chk_depend_of-list of test_ok_1
self.assertIn(test_host_0_test_ok_0, [x[0] for x in test_host_0_test_ok_1.chk_depend_of])
self.assertIn(test_host_1_test_ok_0, [x[0] for x in test_host_1_test_ok_1.chk_depend_of])
# and not vice versa
self.assertNotIn(test_host_0_test_ok_1, [x[0] for x in test_host_0_test_ok_0.chk_depend_of])
self.assertNotIn(test_host_1_test_ok_1, [x[0] for x in test_host_1_test_ok_0.chk_depend_of])
# test_ok_0 is also in the act_depend_of-list of test_ok_1
self.assertIn(test_host_0_test_ok_0, [x[0] for x in test_host_0_test_ok_1.chk_depend_of])
self.assertIn(test_host_1_test_ok_0, [x[0] for x in test_host_1_test_ok_1.chk_depend_of])
# check the criteria
# execution_failure_criteria u,c
# notification_failure_criteria u,c,w
self.assertEqual([x[1] for x in test_host_0_test_ok_1.chk_depend_of if x[0] is test_host_0_test_ok_0], [['u', 'c']] )
self.assertEqual([x[1] for x in test_host_1_test_ok_1.chk_depend_of if x[0] is test_host_1_test_ok_0], [['u', 'c']] )
self.assertEqual([x[1] for x in test_host_0_test_ok_1.act_depend_of if x[0] is test_host_0_test_ok_0], [['u', 'c', 'w']] )
self.assertEqual([x[1] for x in test_host_1_test_ok_1.act_depend_of if x[0] is test_host_1_test_ok_0], [['u', 'c', 'w']] )
# and every service has the host in it's act_depend_of-list
self.assertIn(test_host_0, [x[0] for x in test_host_0_test_ok_0.act_depend_of])
self.assertIn(test_host_0, [x[0] for x in test_host_0_test_ok_1.act_depend_of])
self.assertIn(test_host_1, [x[0] for x in test_host_1_test_ok_0.act_depend_of])
self.assertIn(test_host_1, [x[0] for x in test_host_1_test_ok_1.act_depend_of])
# and final count the masters
self.assertEqual(0, len(test_host_0_test_ok_0.chk_depend_of))
self.assertEqual(1, len(test_host_0_test_ok_1.chk_depend_of))
self.assertEqual(0, len(test_host_1_test_ok_0.chk_depend_of))
self.assertEqual(1, len(test_host_1_test_ok_1.chk_depend_of))
self.assertEqual(1, len(test_host_0_test_ok_0.act_depend_of)) # same, plus the host
self.assertEqual(2, len(test_host_0_test_ok_1.act_depend_of))
self.assertEqual(1, len(test_host_1_test_ok_0.act_depend_of))
self.assertEqual(2, len(test_host_1_test_ok_1.act_depend_of))
def test_host_dependencies(self):
self.print_header()
now = time.time()
#
# A <------ B <--
# ^ \--- C
# |---------------------
#
host_A = self.sched.hosts.find_by_name("test_host_A")
host_B = self.sched.hosts.find_by_name("test_host_B")
host_C = self.sched.hosts.find_by_name("test_host_C")
host_D = self.sched.hosts.find_by_name("test_host_D")
# the most important: test_ok_0 is in the chk_depend_of-list of test_ok_1
#self.assertTrue(host_A in [x[0] for x in host_C.chk_depend_of])
print(host_C.act_depend_of)
print(host_C.chk_depend_of)
print(host_C.chk_depend_of_me)
self.assertIn(host_B, [x[0] for x in host_C.act_depend_of])
self.assertIn(host_A, [x[0] for x in host_C.act_depend_of])
self.assertIn(host_A, [x[0] for x in host_B.act_depend_of])
self.assertEqual([], host_A.act_depend_of)
self.assertIn(host_B, [x[0] for x in host_C.chk_depend_of])
self.assertIn(host_A, [x[0] for x in host_C.chk_depend_of])
self.assertIn(host_A, [x[0] for x in host_B.chk_depend_of])
self.assertEqual([], host_A.act_depend_of)
self.assertIn(host_B, [x[0] for x in host_A.act_depend_of_me])
self.assertIn(host_C, [x[0] for x in host_A.act_depend_of_me])
self.assertIn(host_C, [x[0] for x in host_B.act_depend_of_me])
#self.assertEqual([], host_C.act_depend_of_me) # D in here
self.assertIn(host_B, [x[0] for x in host_A.chk_depend_of_me])
self.assertIn(host_C, [x[0] for x in host_A.chk_depend_of_me])
self.assertIn(host_C, [x[0] for x in host_B.chk_depend_of_me])
self.assertIn(host_D, [x[0] for x in host_C.chk_depend_of_me])
# check the notification/execution criteria
self.assertEqual([['d', 'u']], [x[1] for x in host_C.act_depend_of if x[0] is host_B])
self.assertEqual([['d']], [x[1] for x in host_C.chk_depend_of if x[0] is host_B])
self.assertEqual([['d', 'u']], [x[1] for x in host_C.act_depend_of if x[0] is host_A])
self.assertEqual([['d']], [x[1] for x in host_C.chk_depend_of if x[0] is host_A])
self.assertEqual([['d', 'u']], [x[1] for x in host_B.act_depend_of if x[0] is host_A])
self.assertEqual([['n']], [x[1] for x in host_B.chk_depend_of if x[0] is host_A])
def test_host_inherits_dependencies(self):
self.print_header()
now = time.time()
#
# A <------ B <--
# ^ \--- C <-- D
# |---------------------
#
host_A = self.sched.hosts.find_by_name("test_host_A")
host_B = self.sched.hosts.find_by_name("test_host_B")
host_C = self.sched.hosts.find_by_name("test_host_C")
host_D = self.sched.hosts.find_by_name("test_host_D")
print("A depends on", ",".join([x[0].get_name() for x in host_A.chk_depend_of]))
print("B depends on", ",".join([x[0].get_name() for x in host_B.chk_depend_of]))
print("C depends on", ",".join([x[0].get_name() for x in host_C.chk_depend_of]))
print("D depends on", ",".join([x[0].get_name() for x in host_D.chk_depend_of]))
self.assertEqual([], host_A.act_depend_of)
self.assertIn(host_A, [x[0] for x in host_B.act_depend_of])
self.assertIn(host_A, [x[0] for x in host_C.act_depend_of])
self.assertIn(host_B, [x[0] for x in host_C.act_depend_of])
self.assertIn(host_C, [x[0] for x in host_D.act_depend_of])
# and through inherits_parent....
#self.assertTrue(host_A in [x[0] for x in host_D.act_depend_of])
#self.assertTrue(host_B in [x[0] for x in host_D.act_depend_of])
# Now test a in service service_dep definition. More easierto use than create a full new object
def test_in_servicedef_dep(self):
svc_parent = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "test_parent_svc")
svc_son = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "test_son_svc")
print("DumP", self.conf.servicedependencies)
# the most important: test_parent is in the chk_depend_of-list of test_son
print("Dep: ", svc_son.act_depend_of)
self.assertEqual([x[1] for x in svc_son.act_depend_of if x[0] is svc_parent], [['u', 'c', 'w']] )
def test_host_non_inherits_dependencies(self):
#
# A <------ B <--
# ^ \NOT/--- C <-- D
# |---------------------
#
host_A = self.sched.hosts.find_by_name("test_host_A")
host_B = self.sched.hosts.find_by_name("test_host_B")
host_C = self.sched.hosts.find_by_name("test_host_C")
host_D = self.sched.hosts.find_by_name("test_host_D")
host_E = self.sched.hosts.find_by_name("test_host_E")
print("A depends on", ",".join([x[0].get_name() for x in host_A.chk_depend_of]))
print("B depends on", ",".join([x[0].get_name() for x in host_B.chk_depend_of]))
print("C depends on", ",".join([x[0].get_name() for x in host_C.chk_depend_of]))
print("D depends on", ",".join([x[0].get_name() for x in host_D.chk_depend_of]))
print("E depends on", ",".join([x[0].get_name() for x in host_E.chk_depend_of]))
host_C.state = 'DOWN'
print("D state", host_D.state)
print("E dep", host_E.chk_depend_of)
print("I raise?", host_D.do_i_raise_dependency('d', inherit_parents=False))
# If I ask D for dep, he should raise Nothing if we do not want parents.
self.assertFalse(host_D.do_i_raise_dependency('d', inherit_parents=False) )
# But he should raise a problem (C here) of we ask for its parents
self.assertTrue(host_D.do_i_raise_dependency('d', inherit_parents=True) )
def test_check_dependencies(self):
self.print_header()
now = time.time()
test_host_0 = self.sched.hosts.find_by_name("test_host_0")
test_host_0.checks_in_progress = []
test_host_0.act_depend_of = [] # ignore the router
test_host_0_test_ok_0 = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
# The pending state is always different. Let assume it OK
test_host_0.state = 'OK'
# Create a fake check already done for service
cs = Check('waitconsume', 'foo', test_host_0_test_ok_0, now)
cs.exit_status = 2
cs.output = 'BAD'
cs.check_time = now
cs.execution_time = now
# Create a fake check for the host (so that it is in checking)
ch = Check('scheduled', 'foo', test_host_0, now)
test_host_0.checks_in_progress.append(ch)
# This service should have his host dep
self.assertNotEqual(0, len(test_host_0_test_ok_0.act_depend_of))
# Ok we are at attempt 0 (we should have a 1 with the OK state, but nervermind)
self.assertEqual(0, test_host_0.attempt)
# Add the check to sched queue
self.sched.add(cs)
self.sched.add(ch)
# This should raise a log entry and schedule the host check now
self.sched.consume_results()
# Take the host check. The one generated by dependency not the usual one
c_dep = test_host_0.actions[1]
self.assertTrue(bool(c_dep.dependency_check))
# Hack it to consider it as down and returning critical state
c_dep.status = 'waitconsume'
c_dep.exit_status = 2
c_dep.output = 'BAD'
c_dep.check_time = now
c_dep.execution_time = now
# Add and process result
self.sched.add(c_dep)
self.sched.consume_results()
# We should not have a new attempt as it was a depency check.
self.assertEqual(0, test_host_0.attempt)
def test_disabled_host_service_dependencies(self):
self.print_header()
now = time.time()
test_host_0 = self.sched.hosts.find_by_name("test_host_0")
test_host_0.checks_in_progress = []
test_host_0.act_depend_of = [] # ignore the router
test_host_0_test_ok_0_d = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0_disbld_hst_dep")
self.assertEqual(0, len(test_host_0_test_ok_0_d.act_depend_of))
self.assertNotIn(test_host_0_test_ok_0_d, [x[0] for x in test_host_0.act_depend_of_me])
if __name__ == '__main__':
import cProfile
command = """unittest.main()"""
unittest.main()
#cProfile.runctx( command, globals(), locals(), filename="Thruk.profile" )
| 13,227
|
Python
|
.py
| 224
| 51.008929
| 130
| 0.618846
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,312
|
test_hosts.py
|
shinken-solutions_shinken/test/test_hosts.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
import copy
from shinken_test import *
class TestHost(ShinkenTest):
# setUp is inherited from ShinkenTest
def get_hst(self):
return self.sched.hosts.find_by_name("test_host_0")
# Look if get_*_name return the good result
def test_get_name(self):
hst = self.get_hst()
print(hst.get_dbg_name())
self.assertEqual('test_host_0', hst.get_name())
self.assertEqual('test_host_0', hst.get_dbg_name())
# getstate should be with all properties in dict class + id
# check also the setstate
def test___getstate__(self):
hst = self.get_hst()
cls = hst.__class__
# We get the state
state = hst.__getstate__()
# Check it's the good length
self.assertEqual(len(cls.properties) + len(cls.running_properties) + 1, len(state))
# we copy the service
hst_copy = copy.copy(hst)
# reset the state in the original service
hst.__setstate__(state)
# And it should be the same:then before :)
for p in cls.properties:
## print(getattr(hst_copy, p))
## print(getattr(hst, p))
self.assertEqual(getattr(hst, p), getattr(hst_copy, p) )
# Look if it can detect all incorrect cases
def test_is_correct(self):
hst = self.get_hst()
# first it's ok
self.assertEqual(True, hst.is_correct())
# Now try to delete a required property
max_check_attempts = hst.max_check_attempts
del hst.max_check_attempts
self.assertEqual(True, hst.is_correct())
hst.max_check_attempts = max_check_attempts
###
### Now special cases
###
# no check command
check_command = hst.check_command
del hst.check_command
self.assertEqual(False, hst.is_correct())
hst.check_command = check_command
self.assertEqual(True, hst.is_correct())
# no notification_interval
notification_interval = hst.notification_interval
del hst.notification_interval
self.assertEqual(False, hst.is_correct())
hst.notification_interval = notification_interval
self.assertEqual(True, hst.is_correct())
# Look for set/unset impacted states (unknown)
def test_impact_state(self):
hst = self.get_hst()
ori_state = hst.state
ori_state_id = hst.state_id
hst.set_impact_state()
self.assertEqual('UNREACHABLE', hst.state)
self.assertEqual(2, hst.state_id)
hst.unset_impact_state()
self.assertEqual(ori_state, hst.state)
self.assertEqual(ori_state_id, hst.state_id)
def test_states_from_exit_status(self):
hst = self.get_hst()
# First OK
self.scheduler_loop(1, [[hst, 0, 'OK']])
self.assertEqual('UP', hst.state)
self.assertEqual(0, hst.state_id)
self.assertEqual(True, hst.is_state('UP'))
self.assertEqual(True, hst.is_state('o'))
# Then warning
self.scheduler_loop(1, [[hst, 1, 'WARNING']])
self.assertEqual('UP', hst.state)
self.assertEqual(0, hst.state_id)
self.assertEqual(True, hst.is_state('UP'))
self.assertEqual(True, hst.is_state('o'))
# Then Critical
self.scheduler_loop(1, [[hst, 2, 'CRITICAL']])
self.assertEqual('DOWN', hst.state)
self.assertEqual(1, hst.state_id)
self.assertEqual(True, hst.is_state('DOWN'))
self.assertEqual(True, hst.is_state('d'))
# And unknown
self.scheduler_loop(1, [[hst, 3, 'UNKNOWN']])
self.assertEqual('DOWN', hst.state)
self.assertEqual(1, hst.state_id)
self.assertEqual(True, hst.is_state('DOWN'))
self.assertEqual(True, hst.is_state('d'))
# And something else :)
self.scheduler_loop(1, [[hst, 99, 'WTF THE PLUGIN DEV DID? :)']])
self.assertEqual('DOWN', hst.state)
self.assertEqual(1, hst.state_id)
self.assertEqual(True, hst.is_state('DOWN'))
self.assertEqual(True, hst.is_state('d'))
# And a special case: use_aggressive_host_checking
hst.__class__.use_aggressive_host_checking = True
self.scheduler_loop(1, [[hst, 1, 'WARNING SHOULD GO DOWN']])
self.assertEqual('DOWN', hst.state)
self.assertEqual(1, hst.state_id)
self.assertEqual(True, hst.is_state('DOWN'))
self.assertEqual(True, hst.is_state('d'))
def test_hostgroup(self):
hg = self.conf.hostgroups.find_by_name("hostgroup_01")
self.assertIsNot(hg, None)
h = self.conf.hosts.find_by_name('test_host_0')
self.assertIn(h, hg.members)
self.assertIn(hg.get_name(), [hg.get_name() for hg in h.hostgroups])
def test_childs(self):
h = self.sched.hosts.find_by_name('test_host_0')
r = self.sched.hosts.find_by_name('test_router_0')
# Search if h is in r.childs
self.assertIn(h, r.childs)
# and the reverse
self.assertIn(r, h.parents)
print("r.childs", r.childs)
print("h.childs", h.childs)
# And also in the parent/childs dep list
self.assertIn(h, r.child_dependencies)
# and the reverse
self.assertIn(r, h.parent_dependencies)
if __name__ == '__main__':
unittest.main()
| 6,291
|
Python
|
.py
| 149
| 34.765101
| 91
| 0.640635
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,313
|
test_service_generators.py
|
shinken-solutions_shinken/test/test_service_generators.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_service_generators.cfg')
def test_service_generators(self):
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
print("All service of", "test_host_0")
for s in host.services:
print(s.get_name())
# We ask for 4 services with our disks :)
svc_c = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service C")
svc_d = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service D")
svc_e = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service E")
svc_f = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service F")
svc_g = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service G")
self.assertIsNot(svc_c, None)
self.assertIsNot(svc_d, None)
self.assertIsNot(svc_e, None)
self.assertIsNot(svc_f, None)
self.assertIsNot(svc_g, None)
# two classics
self.assertEqual(['C', '80%', '90%'], svc_c.check_command.args)
self.assertEqual(['D', '95%', '70%'], svc_d.check_command.args)
# a default parameters
self.assertEqual(['E', '38%', '24%'], svc_e.check_command.args)
# and another one
self.assertEqual(['F', '95%', '70%'], svc_f.check_command.args)
# and the tricky last one (with no value :) )
self.assertEqual(['G', '38%', '24%'], svc_g.check_command.args)
# Now check that the dependencies are also created as Generated Service C Dependant -> Generated Service C
svc_c_dep = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service C Dependant")
self.assertIsNot(svc_c_dep, None)
# Dep version should a child of svc
self.assertIn(svc_c_dep, svc_c.child_dependencies)
# But not on other of course
self.assertNotIn(svc_c_dep, svc_d.child_dependencies)
def test_service_generators_not(self):
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
print("All service of", "test_host_0")
for s in host.services:
print(s.get_name())
# We ask for 4 services with our disks :)
svc_c = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service NOT C")
svc_d = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service NOT D")
svc_e = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service NOT E")
svc_f = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service NOT F")
svc_g = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Generated Service NOT G")
self.assertIsNot(svc_c, None)
self.assertIsNot(svc_d, None)
self.assertIs(None, svc_e)
self.assertIs(None, svc_f)
self.assertIsNot(svc_g, None)
def test_service_generators_key_generator(self):
host = self.sched.hosts.find_by_name("sw_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
print("All service of", "sw_0")
for s in host.services:
print(s.get_name())
# We ask for our 6*46 + 6 services with our ports :)
# _ports Unit [1-6] Port [0-46]$(80%!90%)$,Unit [1-6] Port 47$(80%!90%)$
for unit_id in range(1, 7):
for port_id in range(0, 47):
n = "Unit %d Port %d" % (unit_id, port_id)
print("Look for port", 'Generated Service ' + n)
svc = self.sched.services.find_srv_by_name_and_hostname("sw_0", 'Generated Service ' + n)
self.assertIsNot(svc, None)
for unit_id in range(1, 7):
port_id = 47
n = "Unit %d Port %d" % (unit_id, port_id)
print("Look for port", 'Generated Service ' + n)
svc = self.sched.services.find_srv_by_name_and_hostname("sw_0", 'Generated Service ' + n)
self.assertIsNot(svc, None)
def test_service_generators_array(self):
host = self.sched.hosts.find_by_name("sw_1")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
print("All service of", "sw_1")
for s in host.services:
print(s.get_name())
svc = self.sched.services.find_srv_by_name_and_hostname("sw_1", 'Generated Service Gigabit0/1')
self.assertIsNot(svc, None)
self.assertEqual('check_service!1!80%!90%', svc.check_command.call)
svc = self.sched.services.find_srv_by_name_and_hostname("sw_1", 'Generated Service Gigabit0/2')
self.assertIsNot(svc, None)
self.assertEqual('check_service!2!80%!90%', svc.check_command.call)
svc = self.sched.services.find_srv_by_name_and_hostname("sw_1", 'Generated Service Ethernet0/1')
self.assertIsNot(svc, None)
self.assertEqual('check_service!3!80%!95%', svc.check_command.call)
svc = self.sched.services.find_srv_by_name_and_hostname("sw_1", 'Generated Service ISDN1')
self.assertIsNot(svc, None)
self.assertEqual('check_service!4!80%!95%', svc.check_command.call)
def test_service_inherited_description(self):
s1 = self.sched.services.find_srv_by_name_and_hostname("r1", 'SSH')
s2 = self.sched.services.find_srv_by_name_and_hostname("r2", 'SSH')
self.assertIsNotNone(s1)
self.assertIsNotNone(s2)
def test_key_as_descr(self):
svc_h = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "Generated Service H")
svc_i = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "Generated Service I")
svc_j = self.sched.services.find_srv_by_name_and_hostname("test_host_2", "Generated Service J")
svc_k = self.sched.services.find_srv_by_name_and_hostname("test_host_2", "Generated Service K")
svc_l1 = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "Generated Service L")
svc_m1 = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "Generated Service M")
svc_l2 = self.sched.services.find_srv_by_name_and_hostname("test_host_2", "Generated Service L")
svc_m2 = self.sched.services.find_srv_by_name_and_hostname("test_host_2", "Generated Service M")
self.assertIsNotNone(svc_h)
self.assertIsNotNone(svc_i)
self.assertIsNotNone(svc_j)
self.assertIsNotNone(svc_k)
self.assertIsNotNone(svc_l1)
self.assertIsNotNone(svc_m1)
self.assertIsNotNone(svc_l2)
self.assertIsNotNone(svc_m2)
if __name__ == '__main__':
unittest.main()
| 8,492
|
Python
|
.py
| 151
| 48.13245
| 117
| 0.651059
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,314
|
test_external_mapping.py
|
shinken-solutions_shinken/test/test_external_mapping.py
|
#!/usr/bin/env python
#
# Copyright (C) 2012:
# Hartmut Goebel <h.goebel@crazy-compilers.com>
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
"""
Test libexec/external_mapping.py
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import time
import subprocess
import unittest
from tempfile import NamedTemporaryFile
from shinken_test import *
try:
import json
except ImportError:
# For old Python version, load
# simple json (it can be hard json?! It's 2 functions guy!)
try:
import simplejson as json
except ImportError:
print("Error: you need the json or simplejson module")
raise
external_mapping = os.path.join(os.path.dirname(__file__),
'..', 'libexec', 'external_mapping.py')
class TestExternalMapping(ShinkenTest):
def setUp(self):
time_hacker.set_real_time()
def __setup(self, inputlines):
"""
Create a temporary input file and a temporary output-file.
"""
# create output file fist, so it is older
outputfile = NamedTemporaryFile("w", suffix='.json', delete=False)
outputfile.write('--- empty marker ---')
outputfile.close()
self.output_filename = outputfile.name
time.sleep(1) # ensure a time-difference between files
inputfile = NamedTemporaryFile("w", suffix='.txt', delete=False)
for line in inputlines:
inputfile.writelines((line, '\n'))
inputfile.close()
self.input_filename = inputfile.name
def __cleanup(self):
"""
Cleanup the temporary files.
"""
os.remove(self.input_filename)
os.remove(self.output_filename)
def __run(self, lines):
self.__setup(lines)
subprocess.call([external_mapping,
'--input', self.input_filename,
'--output', self.output_filename])
with open(self.output_filename) as f:
result = json.load(f)
self.__cleanup()
return result
def test_simple(self):
lines = [
'myhost:vm1',
'yourhost:vm1',
'theirhost:xen3',
]
result = self.__run(lines)
self.assertEqual(result,
[[["host", "myhost"], ["host", "vm1"]],
[["host", "yourhost"], ["host", "vm1"]],
[["host", "theirhost"], ["host", "xen3"]]])
def test_empty(self):
lines = []
result = self.__run(lines)
self.assertEqual(result, [])
def test_spaces_around_names(self):
lines = [
' myhost : vm1 ',
'yourhost :vm1',
'theirhost: xen3 ',
]
result = self.__run(lines)
self.assertEqual(result,
[[["host", "myhost"], ["host", "vm1"]],
[["host", "yourhost"], ["host", "vm1"]],
[["host", "theirhost"], ["host", "xen3"]]])
def test_comment_line(self):
lines = [
'myhost:vm1',
'# this is a comment',
'yourhost:vm1',
]
result = self.__run(lines)
self.assertEqual(result,
[[["host", "myhost"], ["host", "vm1"]],
[["host", "yourhost"], ["host", "vm1"]]])
if __name__ == '__main__':
unittest.main()
| 4,097
|
Python
|
.py
| 112
| 28.053571
| 82
| 0.577554
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,315
|
test_db.py
|
shinken-solutions_shinken/test/test_db.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
from shinken.db import DB
class TestConfig(ShinkenTest):
# setUp is inherited from ShinkenTest
def create_db(self):
self.db = DB(table_prefix='test_')
def test_create_insert_query(self):
self.create_db()
data = {'id': "1", "is_master": True, 'plop': "master of the universe"}
q = self.db.create_insert_query('instances', data)
self.assertEqual("INSERT INTO test_instances (id , is_master , plop ) VALUES ('1' , '1' , 'master of the universe' )", q)
# Now some UTF8 funny characters
data = {'id': "1", "is_master": True, 'plop': '£°é§'}
q = self.db.create_insert_query('instances', data)
#print("Q", q)
c = "INSERT INTO test_instances (id , is_master , plop ) VALUES ('1' , '1' , '£°é§' )"
print(type(q), type(c))
print(len(q), len(c))
self.assertEqual(c, q)
def test_update_query(self):
self.create_db()
data = {'id': "1", "is_master": True, 'plop': "master of the universe"}
where = {'id': "1", "is_master": True}
q = self.db.create_update_query('instances', data, where)
# beware of the last space
print("Q", q)
self.assertEqual("UPDATE test_instances set plop='master of the universe' WHERE id='1' and is_master='1' ", q)
# Now some UTF8 funny characters
data = {'id': "1", "is_master": True, 'plop': u'£°é§'}
where = {'id': "£°é§", "is_master": True}
q = self.db.create_update_query('instances', data, where)
#print("Q", q)
c = "UPDATE test_instances set plop='£°é§' WHERE id='£°é§' and is_master='1'"
self.assertEqual(c.strip(), q.strip())
if __name__ == '__main__':
unittest.main()
| 2,783
|
Python
|
.py
| 60
| 40.833333
| 132
| 0.641474
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,316
|
test_hostgroup_with_void_member.py
|
shinken-solutions_shinken/test/test_hostgroup_with_void_member.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
# test members property with , at the end
class TestHostgroupAndContactGroupWithVoidMember(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_hostgroup_with_void_member.cfg')
def test_me(self):
self.assertTrue(self.sched.conf.is_correct)
if __name__ == '__main__':
unittest.main()
| 1,322
|
Python
|
.py
| 32
| 39.15625
| 82
| 0.760343
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,317
|
test_timeout.py
|
shinken-solutions_shinken/test/test_timeout.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
from shinken.worker import Worker
from multiprocessing import Queue, Manager
from shinken.objects.service import Service
from shinken.objects.host import Host
from shinken.objects.contact import Contact
modconf = Module()
class TestTimeout(ShinkenTest):
def setUp(self):
# we have an external process, so we must un-fake time functions
self.setup_with_file('etc/shinken_check_timeout.cfg')
time_hacker.set_real_time()
def test_notification_timeout(self):
if os.name == 'nt':
return
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
# These queues connect a poller/reactionner with a worker
to_queue = Queue()
#manager = Manager()
from_queue = Queue() #manager.list()
control_queue = Queue()
# This testscript plays the role of the reactionner
# Now "fork" a worker
w = Worker(1, to_queue, from_queue, 1)
w.id = 1
w.i_am_dying = False
# We prepare a notification in the to_queue
c = Contact()
c.contact_name = "mr.schinken"
n = Notification('PROBLEM', 'scheduled', 'libexec/sleep_command.sh 7', '', svc, '', '', id=1)
n.status = "queue"
#n.command = "libexec/sleep_command.sh 7"
n.t_to_go = time.time()
n.contact = c
n.timeout = 2
n.env = {}
n.exit_status = 0
n.module_type = "fork"
nn = n.copy_shell()
# Send the job to the worker
msg = Message(id=0, type='Do', data=nn)
to_queue.put(msg)
w.checks = []
w.returns_queue = from_queue
w.s = to_queue
w.c = control_queue
# Now we simulate the Worker's work() routine. We can't call it
# as w.work() because it is an endless loop
for i in range(1, 10):
w.get_new_checks()
# During the first loop the sleeping command is launched
w.launch_new_checks()
w.manage_finished_checks()
time.sleep(1)
# The worker should have finished it's job now, either correctly or
# with a timeout
o = from_queue.get()
self.assertEqual('timeout', o.status)
self.assertEqual(3, o.exit_status)
self.assertLess(o.execution_time, n.timeout+1)
# Be a good poller and clean up.
to_queue.close()
control_queue.close()
# Now look what the scheduler says to all this
self.sched.actions[n.id] = n
self.sched.put_results(o)
self.show_logs()
self.assert_any_log_match("Contact mr.schinken service notification command 'libexec/sleep_command.sh 7 ' timed out after 2 seconds")
def test_notification_timeout_on_command(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
print(svc.checks_in_progress)
cs = svc.get_checks_in_progress()
self.assertEqual(1, len(cs))
c = cs.pop()
print(c)
print(c.timeout)
self.assertEqual(5, c.timeout)
if __name__ == '__main__':
unittest.main()
| 4,661
|
Python
|
.py
| 115
| 33.565217
| 141
| 0.642131
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,318
|
test_property_override.py
|
shinken-solutions_shinken/test/test_property_override.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test object properties overriding.
#
from __future__ import absolute_import, division, print_function, unicode_literals
import re
from shinken_test import unittest, ShinkenTest
class TestPropertyOverride(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_property_override.cfg')
def test_service_property_override(self):
svc11 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv-svc1")
svc12 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv-svc2")
svc21 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv-svc1")
svc22 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv-svc2")
svc31 = self.sched.services.find_srv_by_name_and_hostname("test_host_03", "srv-svc1")
svc32 = self.sched.services.find_srv_by_name_and_hostname("test_host_03", "srv-svc2")
svc41 = self.sched.services.find_srv_by_name_and_hostname("test_host_04", "srv-svc1")
svc42 = self.sched.services.find_srv_by_name_and_hostname("test_host_04", "srv-svc2")
svc1proc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "proc proc1")
svc1proc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "proc proc2")
svc2proc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "proc proc1")
svc2proc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "proc proc2")
svc3proc1 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_03", "proc proc1")
svc3proc2 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_03", "proc proc2")
svc4proc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_04", "proc proc1")
svc4proc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_04", "proc proc2")
tp24x7 = self.sched.timeperiods.find_by_name("24x7")
tptest = self.sched.timeperiods.find_by_name("testperiod")
cgtest = self.sched.contactgroups.find_by_name("test_contact")
cgadm = self.sched.contactgroups.find_by_name("admins")
cmdsvc = self.sched.commands.find_by_name("check_service")
cmdtest = self.sched.commands.find_by_name("dummy_command")
# Checks we got the objects we need
self.assertIsNot(svc11, None)
self.assertIsNot(svc21, None)
self.assertIsNot(svc1proc1, None)
self.assertIsNot(svc1proc2, None)
self.assertIsNot(svc2proc1, None)
self.assertIsNot(svc2proc2, None)
self.assertIsNot(tp24x7, None)
self.assertIsNot(tptest, None)
self.assertIsNot(cgtest, None)
self.assertIsNot(cgadm, None)
self.assertIsNot(cmdsvc, None)
self.assertIsNot(cmdtest, None)
self.assertIsNot(svc12, None)
self.assertIsNot(svc22, None)
# Check non overriden properies value
for svc in (svc11, svc12, svc1proc1, svc1proc2,
svc21, svc2proc1, svc4proc1, svc4proc2):
self.assertEqual(["test_contact"], svc.contact_groups)
self.assertIs(tp24x7, svc.maintenance_period)
self.assertEqual(1, svc.retry_interval)
self.assertIs(cmdsvc, svc.check_command.command)
self.assertEqual(["w","u","c","r","f","s"], svc.notification_options)
self.assertIs(True, svc.notifications_enabled)
# Check overriden properies value
for svc in (svc22, svc2proc2, svc31, svc32, svc3proc1, svc3proc2,
svc41, svc42):
self.assertEqual(["admins"], svc.contact_groups)
self.assertIs(tptest, svc.maintenance_period)
self.assertEqual(3, svc.retry_interval)
self.assertIs(cmdtest, svc.check_command.command)
self.assertEqual(["c","r"], svc.notification_options)
self.assertIs(False, svc.notifications_enabled)
class TestConfigBroken(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_property_override_broken.cfg')
def test_service_property_override_errors(self):
self.assertFalse(self.conf.conf_is_correct)
# Get the arbiter's log broks
#:w
#[b.prepare() for b in self.broks]
logs = [b.data['log'] for b in self.broks if b.type == 'log']
self.assertEqual(1, len([log for log in logs if re.search('Error: invalid service override syntax: fake', log)]) )
self.assertEqual(1, len([log for log in logs if re.search("Warn: trying to override property 'retry_interval' on service identified by 'fakesrv' but it's unknown for this host", log)]) )
self.assertEqual(1, len([log for log in logs if re.search("Error: trying to override 'host_name', a forbidden property for service 'proc proc2'", log)]) )
if __name__ == '__main__':
unittest.main()
| 5,757
|
Python
|
.py
| 100
| 50.02
| 194
| 0.686236
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,319
|
test_customs_on_service_hosgroups.py
|
shinken-solutions_shinken/test/test_customs_on_service_hosgroups.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestCustomsonservicehosgroups(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_customs_on_service_hosgroups.cfg')
# We look for 3 services: on defined as direct on 1 hosts, on other
# on 2 hsots, and a last one on a hostgroup
def test_check_for_custom_copy_on_serice_hostgroups(self):
# The one host service
svc_one_host = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_on_1_host")
self.assertIsNot(svc_one_host, None)
# The 2 hosts service(s)
svc_two_hosts_1 = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_on_2_hosts")
self.assertIsNot(svc_two_hosts_1, None)
svc_two_hosts_2 = self.sched.services.find_srv_by_name_and_hostname("test_router_0", "test_on_2_hosts")
self.assertIsNot(svc_two_hosts_2, None)
# Then the one defined on a hostgroup
svc_on_group = self.sched.services.find_srv_by_name_and_hostname("test_router_0", "test_on_group")
self.assertIsNot(svc_on_group, None)
# Each one should have customs
self.assertEqual('custvalue', svc_one_host.customs['_CUSTNAME'])
self.assertEqual('custvalue', svc_two_hosts_1.customs['_CUSTNAME'])
self.assertEqual('custvalue', svc_two_hosts_2.customs['_CUSTNAME'])
self.assertEqual('custvalue', svc_on_group.customs['_CUSTNAME'])
if __name__ == '__main__':
unittest.main()
| 2,450
|
Python
|
.py
| 48
| 46.5
| 111
| 0.716918
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,320
|
test_maintenance_period.py
|
shinken-solutions_shinken/test/test_maintenance_period.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
#time.time = original_time_time
#time.sleep = original_time_sleep
from shinken.objects.timeperiod import Timeperiod
class TestMaintPeriod(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_maintenance_period.cfg')
def test_check_defined_maintenance_period(self):
a_24_7 = self.sched.timeperiods.find_by_name("24x7")
print("Get the hosts and services")
test_router_0 = self.sched.hosts.find_by_name("test_router_0")
test_host_0 = self.sched.hosts.find_by_name("test_host_0")
test_nobody = self.sched.hosts.find_by_name("test_nobody")
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_router_0", "test_ok_0")
svc3 = self.sched.services.find_srv_by_name_and_hostname("test_nobody", "test_ok_0")
# Standard links
self.assertEqual(a_24_7, test_router_0.maintenance_period)
self.assertIs(None, test_host_0.maintenance_period)
self.assertIs(None, test_nobody.maintenance_period)
# Now inplicit inheritance
# This one is defined in the service conf
self.assertEqual(a_24_7, svc1.maintenance_period)
# And others are implicitly inherited
self.assertIs(a_24_7, svc2.maintenance_period)
# This one got nothing :)
self.assertIs(None, svc3.maintenance_period)
def test_check_enter_downtime(self):
test_router_0 = self.sched.hosts.find_by_name("test_router_0")
test_host_0 = self.sched.hosts.find_by_name("test_host_0")
test_nobody = self.sched.hosts.find_by_name("test_nobody")
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_router_0", "test_ok_0")
svc3 = self.sched.services.find_srv_by_name_and_hostname("test_nobody", "test_ok_0")
# we want to focus on only one maintenance
test_router_0.maintenance_period = None
test_host_0.maintenance_period = None
test_nobody.maintenance_period = None
svc1.maintenance_period = None
svc2.maintenance_period = None
# be sure we have some time before a new minute begins.
# otherwise we get a race condition and a failed test here.
now = time.time()
x = time.gmtime(now)
while x.tm_sec < 50:
time.sleep(1)
now = time.time()
x = time.gmtime(now)
now = time.time()
print("now it is", time.asctime(time.localtime(now)))
nowday = time.strftime("%A", time.localtime(now + 60)).lower()
soonstart = time.strftime("%H:%M", time.localtime(now + 60))
soonend = time.strftime("%H:%M", time.localtime(now + 180))
range = "%s %s-%s" % (nowday, soonstart, soonend)
print("range is ", range)
t = Timeperiod()
t.timeperiod_name = ''
t.resolve_daterange(t.dateranges, range)
t_next = t.get_next_valid_time_from_t(now)
print("planned start", time.asctime(time.localtime(t_next)))
t_next = t.get_next_invalid_time_from_t(t_next + 1)
print("planned stop ", time.asctime(time.localtime(t_next)))
svc3.maintenance_period = t
self.assertFalse(svc3.in_maintenance)
#
# now let the scheduler run and wait until the maintenance period begins
# it is now 10 seconds before the full minute. run for 30 seconds
# in 1-second-intervals. this should be enough to trigger the downtime
# in 10 seconds from now the downtime starts
print("scheduler_loop start", time.asctime())
self.scheduler_loop(30, [[svc3, 0, 'OK']], do_sleep=True, sleep_time=1)
print("scheduler_loop end ", time.asctime())
self.assertTrue(hasattr(svc3, 'in_maintenance'))
self.assertEqual(1, len(self.sched.downtimes))
try:
print(".........................................")
print(self.sched.downtimes[1])
print("downtime starts", time.asctime(self.sched.downtimes[1].start_time))
print("downtime ends ", time.asctime(self.sched.downtimes[1].end_time))
except Exception:
print("looks like there is no downtime")
pass
self.assertEqual(1, len(svc3.downtimes))
self.assertIn(svc3.downtimes[0], self.sched.downtimes.values())
self.assertTrue(svc3.in_scheduled_downtime)
self.assertTrue(svc3.downtimes[0].fixed)
self.assertTrue(svc3.downtimes[0].is_in_effect)
self.assertFalse(svc3.downtimes[0].can_be_deleted)
self.assertEqual(svc3.downtimes[0].id, svc3.in_maintenance)
#
# now the downtime should expire...
# we already have 20 seconds (after 10 seconds of startup).
# the downtime is 120 seconds long.
# run the remaining 100 seconds plus 5 seconds just to be sure
self.scheduler_loop(105, [[svc3, 0, 'OK']], do_sleep=True, sleep_time=1)
self.assertEqual(0, len(self.sched.downtimes))
self.assertEqual(0, len(svc3.downtimes))
self.assertFalse(svc3.in_scheduled_downtime)
self.assertIs(None, svc3.in_maintenance)
if __name__ == '__main__':
unittest.main()
| 6,324
|
Python
|
.py
| 124
| 43.532258
| 94
| 0.66494
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,321
|
test_global_event_handlers.py
|
shinken-solutions_shinken/test/test_global_event_handlers.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Sebastien Coavoux <s.coavoux@free.fr>
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test acknowledge of problems
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_global_event_handlers.cfg')
def test_global_eh(self):
self.print_header()
# retry_interval 2
# critical notification
# run loop -> another notification
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_02")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
self.assertEqual(True, svc.event_handler_enabled)
self.assertEqual(True, svc.__class__.enable_event_handlers)
self.assertEqual("eventhandler", svc.global_event_handler.command.command_name)
self.scheduler_loop(5, [[svc, 2, 'CRITICAL']])
self.assert_any_log_match('EVENT HANDLER')
print("MY Actions", self.sched.actions)
if __name__ == '__main__':
unittest.main()
| 2,024
|
Python
|
.py
| 46
| 39.282609
| 92
| 0.703515
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,322
|
test_service_template_inheritance.py
|
shinken-solutions_shinken/test/test_service_template_inheritance.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test attribute inheritance and the right order
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_service_template_inheritance.cfg')
def test_action_url(self):
# base-service-prod,no-graph
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
# no-graph,base-service-prod
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_1")
self.assertTrue(svc1.action_url.startswith("/"))
self.assertTrue(svc1.process_perf_data)
self.assertEqual(svc2.action_url, '')
self.assertTrue(svc2.process_perf_data)
print(svc1.tags)
self.assertIn('no-graph', svc1.tags)
self.assertIn('base-service-prod', svc1.tags)
if __name__ == '__main__':
unittest.main()
| 1,792
|
Python
|
.py
| 41
| 39.853659
| 92
| 0.723307
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,323
|
test_snapshot.py
|
shinken-solutions_shinken/test/test_snapshot.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2010:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestSnapshot(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_snapshot.cfg')
def test_dummy(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("GotSNAP")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("GotSNAP", "SRV")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
self.scheduler_loop(5, [[host, 2, 'DOWN'], [svc, 2, 'BAD | value1=0 value2=0']])
self.assertEqual('DOWN', host.state)
self.assertEqual('HARD', host.state_type)
self.assert_any_log_match('HOST SNAPSHOT.*')
self.assert_log_match(2, 'HOST SNAPSHOT.*')
self.assert_any_log_match('SERVICE SNAPSHOT.*')
self.assert_log_match(4, 'SERVICE SNAPSHOT.*')
self.show_and_clear_logs()
broks = self.sched.broks
#[b.prepare() for b in broks]
types = set([b.type for b in broks])
print(types)
self.assertIn('service_snapshot', types)
self.assertIn('host_snapshot', types)
if __name__ == '__main__':
unittest.main()
| 2,379
|
Python
|
.py
| 56
| 37.196429
| 88
| 0.678494
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,324
|
test_parse_perfdata.py
|
shinken-solutions_shinken/test/test_parse_perfdata.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
from shinken.misc.perfdata import Metric, PerfDatas
class TestParsePerfdata(ShinkenTest):
# Uncomment this is you want to use a specific configuration
# for your test
#def setUp(self):
# self.setup_with_file('etc/shinken_parse_perfdata.cfg')
def test_parsing_perfdata(self):
s = 'ramused=1009MB;;;0;1982 swapused=540MB;;;0;3827 memused=1550MB;2973;3964;0;5810'
s = 'ramused=1009MB;;;0;1982'
m = Metric(s)
self.assertEqual('ramused', m.name)
self.assertEqual(1009, m.value)
self.assertEqual('MB', m.uom)
self.assertEqual(None, m.warning)
self.assertEqual(None, m.critical)
self.assertEqual(0, m.min)
self.assertEqual(1982, m.max)
s = 'ramused=90%;85;95;;'
m = Metric(s)
self.assertEqual('ramused', m.name)
self.assertEqual(90, m.value)
self.assertEqual('%', m.uom)
self.assertEqual(85, m.warning)
self.assertEqual(95, m.critical)
self.assertEqual(0, m.min)
self.assertEqual(100, m.max)
s = 'ramused=1009MB;;;0;1982 swapused=540MB;;;; memused=90%'
p = PerfDatas(s)
p.metrics
m = p['swapused']
self.assertEqual('swapused', m.name)
self.assertEqual(540, m.value)
self.assertEqual('MB', m.uom)
self.assertEqual(None, m.warning)
self.assertEqual(None, m.critical)
self.assertEqual(None, m.min)
self.assertEqual(None, m.max)
m = p['memused']
self.assertEqual('memused', m.name)
self.assertEqual(90, m.value)
self.assertEqual('%', m.uom)
self.assertEqual(None, m.warning)
self.assertEqual(None, m.critical)
self.assertEqual(0, m.min)
self.assertEqual(100, m.max)
self.assertEqual(3, len(p))
s = "'Physical Memory Used'=12085620736Bytes; 'Physical Memory Utilisation'=94%;80;90;"
p = PerfDatas(s)
p.metrics
m = p['Physical Memory Used']
self.assertEqual('Physical Memory Used', m.name)
self.assertEqual(12085620736, m.value)
self.assertEqual('Bytes', m.uom)
self.assertIs(None, m.warning)
self.assertIs(None, m.critical)
self.assertIs(None, m.min)
self.assertIs(None, m.max)
m = p['Physical Memory Utilisation']
self.assertEqual('Physical Memory Utilisation', m.name)
self.assertEqual(94, m.value)
self.assertEqual('%', m.uom)
self.assertEqual(80, m.warning)
self.assertEqual(90, m.critical)
self.assertEqual(0, m.min)
self.assertEqual(100, m.max)
s = "'C: Space'=35.07GB; 'C: Utilisation'=87.7%;90;95;"
p = PerfDatas(s)
p.metrics
m = p['C: Space']
self.assertEqual('C: Space', m.name)
self.assertEqual(35.07, m.value)
self.assertEqual('GB', m.uom)
self.assertIs(None, m.warning)
self.assertIs(None, m.critical)
self.assertIs(None, m.min)
self.assertIs(None, m.max)
m = p['C: Utilisation']
self.assertEqual('C: Utilisation', m.name)
self.assertEqual(87.7, m.value)
self.assertEqual('%', m.uom)
self.assertEqual(90, m.warning)
self.assertEqual(95, m.critical)
self.assertEqual(0, m.min)
self.assertEqual(100, m.max)
s = "time_offset-192.168.0.1=-7.22636468709e-05s;1;2;0;;"
p = PerfDatas(s)
m = p['time_offset-192.168.0.1']
self.assertEqual('time_offset-192.168.0.1', m.name)
self.assertEqual(-7.22636468709e-05, m.value)
self.assertEqual('s', m.uom)
self.assertEqual(1, m.warning)
self.assertEqual(2, m.critical)
self.assertEqual(0, m.min)
self.assertIs(None, m.max)
s = u"ééé-192.168.0.1=-7.22636468709e-05s;1;2;0;;"
p = PerfDatas(s)
m = p[u'ééé-192.168.0.1']
self.assertEqual(m.name, u'ééé-192.168.0.1')
self.assertEqual(m.value, -7.22636468709e-05)
self.assertEqual(m.uom, 's')
self.assertEqual(m.warning, 1)
self.assertEqual(m.critical, 2)
self.assertEqual(m.min, 0)
self.assertEqual(m.max, None)
#Test that creating a perfdata with nothing dosen't fail
s = None
p = PerfDatas(s)
self.assertEqual(len(p), 0)
if __name__ == '__main__':
unittest.main()
| 5,423
|
Python
|
.py
| 135
| 32.8
| 95
| 0.637072
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,325
|
test_realms.py
|
shinken-solutions_shinken/test/test_realms.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
import six
from shinken_test import *
class TestRealms(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_realms.cfg')
# We check for each host, if they are in the good realm
def test_realm_assigntion(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
realm1 = self.conf.realms.find_by_name('realm1')
self.assertIsNot(realm1, None)
realm2 = self.conf.realms.find_by_name('realm2')
self.assertIsNot(realm2, None)
test_host_realm1 = self.sched.hosts.find_by_name("test_host_realm1")
self.assertIsNot(test_host_realm1, None)
self.assertEqual(realm1.get_name(), test_host_realm1.realm)
test_host_realm2 = self.sched.hosts.find_by_name("test_host_realm2")
self.assertIsNot(test_host_realm2, None)
self.assertEqual(realm2.get_name(), test_host_realm2.realm)
# We check for each host, if they are in the good realm
# but when they are apply in a hostgroup link
def test_realm_hostgroup_assigntion(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
in_realm2 = self.sched.hostgroups.find_by_name('in_realm2')
realm1 = self.conf.realms.find_by_name('realm1')
self.assertIsNot(realm1, None)
realm2 = self.conf.realms.find_by_name('realm2')
self.assertIsNot(realm2, None)
# 1 and 2 are link to realm2 because they are in the hostgroup in_realm2
test_host1_hg_realm2 = self.sched.hosts.find_by_name("test_host1_hg_realm2")
self.assertIsNot(test_host1_hg_realm2, None)
self.assertEqual(realm2.get_name(), test_host1_hg_realm2.realm)
self.assertIn(in_realm2.get_name(), [hg.get_name() for hg in test_host1_hg_realm2.hostgroups])
test_host2_hg_realm2 = self.sched.hosts.find_by_name("test_host2_hg_realm2")
self.assertIsNot(test_host2_hg_realm2, None)
self.assertEqual(realm2.get_name(), test_host2_hg_realm2.realm)
self.assertIn(in_realm2.get_name(), [hg.get_name() for hg in test_host2_hg_realm2.hostgroups])
test_host3_hg_realm2 = self.sched.hosts.find_by_name("test_host3_hg_realm2")
self.assertIsNot(test_host3_hg_realm2, None)
self.assertEqual(realm1.get_name(), test_host3_hg_realm2.realm)
self.assertIn(in_realm2.get_name(), [hg.get_name() for hg in test_host3_hg_realm2.hostgroups])
# Realms should be stripped when linking to hosts and hostgroups
# so we don't pickle the whole object, but just a name
def test_realm_stripping_before_sending(self):
test_host_realm1 = self.sched.hosts.find_by_name("test_host_realm1")
self.assertIsNot(test_host_realm1, None)
self.assertTrue(isinstance(test_host_realm1.realm, six.string_types))
in_realm2 = self.sched.hostgroups.find_by_name('in_realm2')
self.assertIsNot(in_realm2, None)
self.assertTrue(isinstance(in_realm2.realm, six.string_types))
def test_sub_realms_assignations(self):
world = self.conf.realms.find_by_name('World')
self.assertIsNot(world, None)
europe = self.conf.realms.find_by_name('Europe')
self.assertIsNot(europe, None)
paris = self.conf.realms.find_by_name('Paris')
self.assertIsNot(paris, None)
# Get the broker in the realm level
bworld = self.conf.brokers.find_by_name('B-world')
self.assertIsNot(bworld, None)
world.prepare_for_satellites_conf()
europe.prepare_for_satellites_conf()
paris.prepare_for_satellites_conf()
# broker should be in the world level
self.assertIs(bworld in world.potential_brokers, True)
# in europe too
self.assertIs(bworld in europe.potential_brokers, True)
# and in paris too
self.assertIs(bworld in paris.potential_brokers, True)
if __name__ == '__main__':
unittest.main()
| 5,118
|
Python
|
.py
| 103
| 43.029126
| 102
| 0.692154
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,326
|
test_acknowledge.py
|
shinken-solutions_shinken/test/test_acknowledge.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test acknowledge of problems
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
from shinken.serializer import serialize, deserialize
class TestAcks(ShinkenTest):
def test_ack_soft_service(self):
self.print_header()
# retry_interval 2
# critical notification
# run loop -> another notification
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']])
print("- 1 x OK -------------------------------------")
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(0, svc.current_notification_number)
#--------------------------------------------------------------
# first check the normal behavior
# service reaches hard;2
# at the end there must be 3 actions: eventhandler hard,
# master notification and contact notification
#--------------------------------------------------------------
print("- 2 x BAD get hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']])
self.assertEqual(1, svc.current_notification_number)
self.assertEqual(3, self.count_actions())
self.assert_log_match(5, 'SERVICE NOTIFICATION')
self.show_and_clear_logs()
self.show_and_clear_actions()
# clean up
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.clear_logs()
self.clear_actions()
#--------------------------------------------------------------
# service reaches soft;1
# there must not be any notification
#--------------------------------------------------------------
print("- 1 x BAD get soft -------------------------------------")
self.scheduler_loop(1, [[svc, 2, 'BAD']])
self.assertEqual(0, svc.current_notification_number)
#--------------------------------------------------------------
# someone acknowledges the problem before a notification goes out
#--------------------------------------------------------------
self.assertFalse(svc.problem_has_been_acknowledged)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;1;1;0;lausser;blablub" % now
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [], do_sleep=False)
#self.sched.get_new_actions()
#self.worker_loop()
self.assertTrue(svc.problem_has_been_acknowledged)
self.assert_log_match(3, 'ACKNOWLEDGEMENT \(CRITICAL\)')
self.show_and_clear_logs()
self.show_actions()
self.sched.update_downtimes_and_comments()
self.assertEqual(1, len(svc.comments))
#--------------------------------------------------------------
# service reaches hard;2
# a notification must have been created but blocked
# log for alert hard and log for eventhandler
#--------------------------------------------------------------
print("- 1 x BAD get hard -------------------------------------")
self.scheduler_loop(1, [[svc, 2, 'BAD']])
self.assertEqual(2, self.count_logs())
self.assertEqual(2, self.count_actions())
self.assertEqual(0, svc.current_notification_number)
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# recover
# the acknowledgement must have been removed automatically
#--------------------------------------------------------------
self.scheduler_loop(1, [[svc, 0, 'GOOD']])
print("- 1 x OK recover")
self.show_logs()
self.show_actions()
self.assertEqual(2, self.count_logs()) # alert, eventhndlr
self.assertEqual(1, self.count_actions()) # evt zombie
self.assertFalse(svc.problem_has_been_acknowledged)
self.assertEqual(0, svc.current_notification_number)
self.show_and_clear_logs()
self.show_and_clear_actions()
def test_ack_hard_service(self):
self.print_header()
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']])
print("- 1 x OK -------------------------------------")
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(0, svc.current_notification_number)
#--------------------------------------------------------------
# first check the normal behavior
# service reaches hard;2
# at the end there must be 3 actions: eventhandler hard,
# master notification and contact notification
#--------------------------------------------------------------
print("- 2 x BAD get hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']])
self.assertEqual(1, svc.current_notification_number)
self.assertEqual(3, self.count_actions())
self.assert_log_match(5, 'SERVICE NOTIFICATION')
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# stay hard and wait for the second notification (notification_interval)
#--------------------------------------------------------------
print("- 2 x BAD stay hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=True)
self.show_and_clear_logs()
self.show_actions()
self.assertEqual(2, svc.current_notification_number)
#--------------------------------------------------------------
# admin wakes up and acknowledges the problem
# the ACK is the only log message
# a master notification is still around, but can't be sent
#--------------------------------------------------------------
self.assertFalse(svc.problem_has_been_acknowledged)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;1;1;0;lausser;blablub" % now
self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.scheduler_loop(1, [], do_sleep=False)
#self.worker_loop()
self.assertTrue(svc.problem_has_been_acknowledged)
self.assert_log_match(1, 'ACKNOWLEDGEMENT \(CRITICAL\)')
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=True)
self.assertEqual(1, self.count_logs())
self.assertEqual(1, self.count_actions())
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# remove acknowledgement
# now notifications are sent again
#--------------------------------------------------------------
now = time.time()
cmd = "[%lu] REMOVE_SVC_ACKNOWLEDGEMENT;test_host_0;test_ok_0" % now
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [], do_sleep=False)
#elf.sched.get_new_actions()
#self.worker_loop()
self.show_logs()
self.show_actions()
# the contact notification was sent immediately (t_to_go)
self.assertFalse(svc.problem_has_been_acknowledged)
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=True)
self.show_logs()
self.show_actions()
self.assert_log_match(1, 'SERVICE NOTIFICATION')
self.assert_log_match(2, 'SERVICE NOTIFICATION')
self.assertEqual(2, self.count_logs())
self.assertEqual(2, self.count_actions()) # master sched, contact zombie
self.assertEqual(4, svc.current_notification_number)
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# recover
# the acknowledgement must have been removed automatically
# recover notifications are only sent to contacts which
# received a critical/warning notification
#--------------------------------------------------------------
self.scheduler_loop(1, [[svc, 0, 'GOOD']])
print("- 1 x OK recover")
self.show_logs()
self.show_actions()
self.assertEqual(3, self.count_logs()) # alert, eventhndlr, notif
self.show_actions()
print(self.count_actions())
self.assertEqual(2, self.count_actions()) # evt, recovery notif zombie
self.assertFalse(svc.problem_has_been_acknowledged)
self.assertEqual(0, svc.current_notification_number)
self.show_and_clear_logs()
self.show_and_clear_actions()
def test_ack_nonsticky_changing_service(self):
# acknowledge is not sticky
# service goes from critical to warning
# this means, the acknowledge deletes itself
self.print_header()
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']])
print("- 1 x OK -------------------------------------")
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(0, svc.current_notification_number)
#--------------------------------------------------------------
# first check the normal behavior
# service reaches hard;2
# at the end there must be 3 actions: eventhandler hard,
# master notification and contact notification
#--------------------------------------------------------------
print("- 2 x BAD get hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']])
self.assertEqual(1, svc.current_notification_number)
self.assertEqual(3, self.count_actions())
self.assert_log_match(5, 'SERVICE NOTIFICATION')
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# stay hard and wait for the second notification (notification_interval)
#--------------------------------------------------------------
print("- 2 x BAD stay hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=True)
self.show_and_clear_logs()
self.show_actions()
self.assertEqual(2, svc.current_notification_number)
#--------------------------------------------------------------
# admin wakes up and acknowledges the problem
# the ACK is the only log message
# a master notification is still around, but can't be sent
#--------------------------------------------------------------
self.assertFalse(svc.problem_has_been_acknowledged)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;1;1;1;lausser;blablub" % now
self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.scheduler_loop(1, [], do_sleep=False)
#self.worker_loop()
self.assertTrue(svc.problem_has_been_acknowledged)
self.assert_log_match(1, 'ACKNOWLEDGEMENT \(CRITICAL\)')
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=True)
self.assertEqual(1, self.count_logs())
self.assertEqual(1, self.count_actions())
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# now become warning
# ack is deleted automatically and notifications are sent again
#--------------------------------------------------------------
self.scheduler_loop(2, [[svc, 1, 'NOT REALLY BAD']], do_sleep=True)
self.assertFalse(svc.problem_has_been_acknowledged)
self.show_logs()
self.show_actions()
self.assert_log_match(1, 'SERVICE ALERT.*WARNING')
self.assert_log_match(2, 'SERVICE NOTIFICATION')
self.assert_log_match(3, 'SERVICE NOTIFICATION')
self.assertEqual(3, self.count_logs())
self.assertEqual(2, self.count_actions()) # master sched, contact zombie
self.assertEqual(4, svc.current_notification_number)
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# recover
# the acknowledgement must have been removed automatically
#--------------------------------------------------------------
self.scheduler_loop(1, [[svc, 0, 'GOOD']])
print("- 1 x OK recover")
self.show_logs()
self.show_actions()
self.assertEqual(3, self.count_logs()) # alert, eventhndlr, notification
self.show_actions()
self.assertEqual(2, self.count_actions()) # evt, one notif zombie left
self.assertFalse(svc.problem_has_been_acknowledged)
self.assertEqual(0, svc.current_notification_number)
self.show_and_clear_logs()
self.show_and_clear_actions()
def test_ack_sticky_changing_service(self):
# acknowledge is sticky
# service goes from critical to warning
# still acknowledged
self.print_header()
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']])
print("- 1 x OK -------------------------------------")
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(0, svc.current_notification_number)
#--------------------------------------------------------------
# first check the normal behavior
# service reaches hard;2
# at the end there must be 3 actions: eventhandler hard,
# master notification and contact notification
#--------------------------------------------------------------
print("- 2 x BAD get hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']])
self.assertEqual(1, svc.current_notification_number)
self.assertEqual(3, self.count_actions())
self.assert_log_match(5, 'SERVICE NOTIFICATION')
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# stay hard and wait for the second notification (notification_interval)
#--------------------------------------------------------------
print("- 2 x BAD stay hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=True)
self.show_and_clear_logs()
self.show_actions()
self.assertEqual(2, svc.current_notification_number)
#--------------------------------------------------------------
# admin wakes up and acknowledges the problem
# the ACK is the only log message
# a master notification is still around, but can't be sent
#--------------------------------------------------------------
self.assertFalse(svc.problem_has_been_acknowledged)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;2;1;0;lausser;blablub" % now
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [], do_sleep=True)
#self.sched.get_new_actions()
#self.worker_loop()
self.assertTrue(svc.problem_has_been_acknowledged)
self.assert_log_match(1, 'ACKNOWLEDGEMENT \(CRITICAL\)')
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=True)
self.assertEqual(1, self.count_logs())
self.assertEqual(1, self.count_actions())
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# now become warning
# ack remains set
#--------------------------------------------------------------
self.scheduler_loop(2, [[svc, 1, 'NOT REALLY BAD']], do_sleep=True)
self.assertTrue(svc.problem_has_been_acknowledged)
self.show_logs()
self.show_actions()
self.assert_log_match(1, 'SERVICE ALERT.*WARNING')
self.assertEqual(1, self.count_logs()) # alert
self.assertEqual(2, svc.current_notification_number)
self.show_and_clear_logs()
self.show_actions()
self.assertEqual(1, len(svc.comments))
self.assertEqual('blablub', svc.comments[0].comment)
#--------------------------------------------------------------
# recover
# the acknowledgement must have been removed automatically
#--------------------------------------------------------------
self.scheduler_loop(1, [[svc, 0, 'GOOD']])
print("- 1 x OK recover")
self.show_logs()
self.show_actions()
self.assertEqual(3, self.count_logs()) # alert, eventhndlr, notification
self.assertEqual(2, self.count_actions()) # evt, master notif
self.assertFalse(svc.problem_has_been_acknowledged)
self.assertEqual(0, svc.current_notification_number)
self.assertEqual(0, len(svc.comments))
self.show_and_clear_logs()
self.show_and_clear_actions()
def test_ack_soft_host(self):
self.print_header()
# retry_interval 2
# critical notification
# run loop -> another notification
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']])
print("- 1 x OK -------------------------------------")
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(0, host.current_notification_number)
#--------------------------------------------------------------
# first check the normal behavior
# service reaches hard;2
# at the end there must be 3 actions: eventhandler hard,
# master notification and contact notification
#--------------------------------------------------------------
print("- 3 x DOWN get hard -------------------------------------")
self.scheduler_loop(3, [[host, 2, 'DOWN']])
self.assertEqual(1, host.current_notification_number)
self.assertEqual(3, self.count_actions())
self.assert_log_match(7, 'HOST NOTIFICATION')
self.show_and_clear_logs()
self.show_and_clear_actions()
# clean up
self.scheduler_loop(1, [[host, 0, 'UP']])
self.clear_logs()
self.clear_actions()
#--------------------------------------------------------------
# service reaches soft;1
# there must not be any notification
#--------------------------------------------------------------
print("- 1 x BAD get soft -------------------------------------")
self.scheduler_loop(1, [[host, 2, 'DOWN']])
self.assertEqual(0, host.current_notification_number)
#--------------------------------------------------------------
# someone acknowledges the problem before a notification goes out
#--------------------------------------------------------------
self.assertFalse(host.problem_has_been_acknowledged)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_HOST_PROBLEM;test_host_0;1;1;0;lausser;blablub" % now
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [], do_sleep=False)
#self.sched.get_new_actions()
#self.worker_loop()
self.assertTrue(host.problem_has_been_acknowledged)
self.assert_log_match(3, 'ACKNOWLEDGEMENT \(DOWN\)')
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# service reaches hard;2
# a notification must have been created but blocked
# log for alert soft2, hard3 and log for eventhandler soft2, hard3
# eventhandler hard3 (eventhandler soft2 is already zombied when
# the workerloop is finished
#--------------------------------------------------------------
print("- 2 x BAD get hard -------------------------------------")
self.scheduler_loop(2, [[host, 2, 'DOWN']])
self.show_logs()
self.show_actions()
self.assertEqual(4, self.count_logs())
self.assertEqual(2, self.count_actions())
self.assertEqual(0, host.current_notification_number)
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# recover
# the acknowledgement must have been removed automatically
# recover notifications are only sent to contacts which
# received a critical/warning notification
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']])
print("- 1 x OK recover")
self.show_logs()
self.show_actions()
self.assertEqual(2, self.count_logs()) # alert, eventhndlr, notification
self.show_actions()
print(self.count_actions())
self.assertEqual(1, self.count_actions()) # evt, no more notif
self.assertFalse(host.problem_has_been_acknowledged)
self.assertEqual(0, host.current_notification_number)
self.show_and_clear_logs()
self.show_and_clear_actions()
def test_ack_hard_host(self):
self.print_header()
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']])
print("- 1 x OK -------------------------------------")
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(0, host.current_notification_number)
#--------------------------------------------------------------
# first check the normal behavior
# service reaches hard;2
# at the end there must be 3 actions: eventhandler hard,
# master notification and contact notification
#--------------------------------------------------------------
print("- 2 x BAD get hard -------------------------------------")
self.scheduler_loop(3, [[host, 2, 'DOWN']])
self.assertEqual(1, host.current_notification_number)
self.assertEqual(3, self.count_actions())
self.assert_log_match(7, 'HOST NOTIFICATION')
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# stay hard and wait for the second notification (notification_interval)
#--------------------------------------------------------------
print("- 2 x BAD stay hard -------------------------------------")
self.scheduler_loop(2, [[host, 2, 'DOWN']], do_sleep=True)
self.show_and_clear_logs()
self.show_actions()
self.assertEqual(2, host.current_notification_number)
#--------------------------------------------------------------
# admin wakes up and acknowledges the problem
# the ACK is the only log message
# a master notification is still around, but can't be sent
#--------------------------------------------------------------
self.assertFalse(host.problem_has_been_acknowledged)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_HOST_PROBLEM;test_host_0;1;1;0;lausser;blablub" % now
self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.scheduler_loop(1, [], do_sleep=False)
#self.worker_loop()
self.assertTrue(host.problem_has_been_acknowledged)
self.assert_log_match(1, 'ACKNOWLEDGEMENT \(DOWN\)')
self.scheduler_loop(2, [[host, 2, 'DOWN']], do_sleep=True)
self.assertEqual(1, self.count_logs())
self.assertEqual(1, self.count_actions())
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# remove acknowledgement
# now notifications are sent again
#--------------------------------------------------------------
now = time.time()
cmd = "[%lu] REMOVE_HOST_ACKNOWLEDGEMENT;test_host_0" % now
self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.scheduler_loop(1, [], do_sleep=False)
#self.worker_loop()
# the contact notification was sent immediately (t_to_go)
self.assertFalse(host.problem_has_been_acknowledged)
self.scheduler_loop(2, [[host, 2, 'DOWN']], do_sleep=True)
self.show_logs()
self.show_actions()
self.assert_log_match(1, 'HOST NOTIFICATION')
self.assert_log_match(2, 'HOST NOTIFICATION')
self.assertEqual(2, self.count_logs())
self.assertEqual(2, self.count_actions()) # master sched, contact zombie
self.assertEqual(4, host.current_notification_number)
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# recover
# the acknowledgement must have been removed automatically
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'GOOD']])
print("- 1 x OK recover")
self.show_logs()
self.show_actions()
self.assertEqual(3, self.count_logs()) # alert, eventhndlr, notification
print(self.count_actions())
self.show_actions()
self.assertEqual(2, self.count_actions()) # evt, recovery notif zombie
self.assertFalse(host.problem_has_been_acknowledged)
self.assertEqual(0, host.current_notification_number)
self.show_and_clear_logs()
self.show_and_clear_actions()
def test_unack_removes_comments(self):
# critical
# ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;2;1;1;test_contact_alias;ackweb6
# ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;2;1;1;test_contact_alias;ackweb6
# ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;2;1;0;test_contact_alias;acknull
# now remove the ack
# the first two comments remain. So persistent not only means "survice a reboot"
# but also "stay after the ack has been deleted"
self.print_header()
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']])
print("- 1 x OK -------------------------------------")
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(0, svc.current_notification_number)
#--------------------------------------------------------------
# first check the normal behavior
# service reaches hard;2
# at the end there must be 3 actions: eventhandler hard,
# master notification and contact notification
#--------------------------------------------------------------
print("- 2 x BAD get hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']])
self.assertEqual(1, svc.current_notification_number)
self.assertEqual(3, self.count_actions())
self.assert_log_match(5, 'SERVICE NOTIFICATION')
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# stay hard and wait for the second notification (notification_interval)
#--------------------------------------------------------------
print("- 2 x BAD stay hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=True)
self.show_and_clear_logs()
self.show_actions()
self.assertEqual(2, svc.current_notification_number)
#--------------------------------------------------------------
# admin wakes up and acknowledges the problem
# the ACK is the only log message
# a master notification is still around, but can't be sent
#--------------------------------------------------------------
self.assertFalse(svc.problem_has_been_acknowledged)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;2;1;1;lausser;blablub1" % now
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [], do_sleep=True)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;2;1;1;lausser;blablub2" % now
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [], do_sleep=True)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;2;1;0;lausser;blablub3" % now
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [], do_sleep=True)
self.assertTrue(svc.problem_has_been_acknowledged)
self.show_logs()
self.assert_log_match(1, 'ACKNOWLEDGEMENT \(CRITICAL\)')
self.assert_log_match(2, 'ACKNOWLEDGEMENT \(CRITICAL\)')
self.assert_log_match(3, 'ACKNOWLEDGEMENT \(CRITICAL\)')
self.scheduler_loop(1, [[svc, 2, 'BAD']], do_sleep=True)
self.assertEqual(1, self.count_actions())
self.show_and_clear_logs()
self.show_actions()
self.assertEqual(3, len(svc.comments))
print("- 2 x BAD stay hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=True)
self.show_and_clear_logs()
self.show_actions()
self.assertEqual(2, svc.current_notification_number)
#--------------------------------------------------------------
# remove the ack. the 2 persistent comments must remain
#--------------------------------------------------------------
now = time.time()
cmd = "[%lu] REMOVE_SVC_ACKNOWLEDGEMENT;test_host_0;test_ok_0" % now
self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.scheduler_loop(1, [], do_sleep=False)
#self.worker_loop()
self.assertFalse(svc.problem_has_been_acknowledged)
self.assertEqual(2, len(svc.comments))
self.assertEqual('blablub1', svc.comments[0].comment)
self.assertEqual('blablub2', svc.comments[1].comment)
# service is critical, notification is out
# click on ack without setting the sticky checkbox in the webinterface
# EXTERNAL COMMAND: ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;1;1;0;test_contact_alias;weback
# now service is acknowledged and has a comment
# silence...
# service is warning
# notification is sent
# acknowledgement and comment have disappeared
# service is critical, notification is out
# send external command through the pipe 3 times
# ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;1;1;0;test_contact_alias;weback
# ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;1;1;0;test_contact_alias;weback
# ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;1;1;0;test_contact_alias;weback
# now service is acknowledged and has 3 comments
# silence...
# service is warning
# notification is sent
# acknowledgement and comments have disappeared
if __name__ == '__main__':
unittest.main()
| 35,445
|
Python
|
.py
| 683
| 43.379209
| 97
| 0.518646
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,327
|
requirements.py26.txt
|
shinken-solutions_shinken/test/requirements.py26.txt
|
# some packages need to be kept as specific version for
# actually don't link with "normal" one as pip otherwise report conflicting package versions.
# -r ./requirements.txt
# for pylint to succeed with Python2.6 , we actually need all these specific versions:
pylint==1.3.1
astroid==1.2.1
six==1.4.0
# endfor pytlint
| 322
|
Python
|
.py
| 8
| 38.75
| 93
| 0.777419
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,328
|
shinken_test.py
|
shinken-solutions_shinken/test/shinken_test.py
|
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function, unicode_literals
#
# This file is used to test host- and service-downtimes.
#
import six
import sys
from sys import __stdout__
from functools import partial
import time
import datetime
import os
import re
import random
import copy
import locale
import unittest
# import the shinken library from the parent directory
import __import_shinken ; del __import_shinken
import shinken
from shinken.objects.config import Config
from shinken.objects.command import Command
from shinken.objects.module import Module
from shinken.objects.schedulingitem import SchedulingItem
from shinken.dispatcher import Dispatcher
from shinken.log import logger
from shinken.modulesctx import modulesctx
from shinken.scheduler import Scheduler
from shinken.macroresolver import MacroResolver
from shinken.external_command import ExternalCommandManager, ExternalCommand
from shinken.check import Check
from shinken.message import Message
from shinken.objects.arbiterlink import ArbiterLink
from shinken.objects.schedulerlink import SchedulerLink
from shinken.objects.pollerlink import PollerLink
from shinken.objects.reactionnerlink import ReactionnerLink
from shinken.objects.brokerlink import BrokerLink
from shinken.objects.satellitelink import SatelliteLink
from shinken.notification import Notification
from shinken.modulesmanager import ModulesManager
from shinken.basemodule import BaseModule
from shinken.brok import Brok
from shinken.misc.common import DICT_MODATTR
from shinken.daemons.schedulerdaemon import Shinken
from shinken.daemons.brokerdaemon import Broker
from shinken.daemons.arbiterdaemon import Arbiter
from shinken.daemons.receiverdaemon import Receiver
from logging import ERROR
# Modules are by default on the ../modules
myself = os.path.abspath(__file__)
global modules_dir
modules_dir = os.environ.get('SHINKEN_MODULES_DIR', "modules")
class __DUMMY:
def add(self, obj):
pass
logger.load_obj(__DUMMY())
logger.setLevel(ERROR)
#############################################################################
def guess_sys_stdout_encoding():
''' Return the best guessed encoding to be used for printing on sys.stdout. '''
return (
getattr(sys.stdout, 'encoding', None)
or getattr(__stdout__, 'encoding', None)
or locale.getpreferredencoding()
or sys.getdefaultencoding()
or 'ascii'
)
def safe_print(*args, **kw):
"""" "print" args to sys.stdout,
If some of the args aren't unicode then convert them first to unicode,
using keyword argument 'in_encoding' if provided (else default to UTF8)
and replacing bad encoded bytes.
Write to stdout using 'out_encoding' if provided else best guessed encoding,
doing xmlcharrefreplace on errors.
"""
in_bytes_encoding = kw.pop('in_encoding', 'UTF-8')
out_encoding = kw.pop('out_encoding', guess_sys_stdout_encoding())
if kw:
raise ValueError('unhandled named/keyword argument(s): %r' % kw)
#
make_in_data_gen = lambda: (
a if isinstance(a, six.string_types)
else ("%s" % a).encode(in_bytes_encoding, 'replace')
for a in args
)
possible_codings = ( out_encoding, )
if out_encoding != 'ascii':
possible_codings += ( 'ascii', )
for coding in possible_codings:
data = ' '.join(make_in_data_gen()).encode(coding, 'xmlcharrefreplace')
try:
sys.stdout.write(data.decode("utf-8"))
break
except UnicodeError as err:
# there might still have some problem with the underlying sys.stdout.
# it might be a StringIO whose content could be decoded/encoded in this same process
# and have encode/decode errors because we could have guessed a bad encoding with it.
# in such case fallback on 'ascii'
if coding == 'ascii':
raise
sys.stderr.write('Error on write to sys.stdout with %s encoding: err=%s\nTrying with ascii' % (
coding, err))
sys.stdout.write('\n')
#############################################################################
# We overwrite the functions time() and sleep()
# This way we can modify sleep() so that it immediately returns although
# for a following time() it looks like thee was actually a delay.
# This massively speeds up the tests.
class TimeHacker(object):
def __init__(self):
self.my_offset = 0
self.my_starttime = time.time()
self.my_oldtime = time.time
self.original_time_time = time.time
self.original_time_sleep = time.sleep
self.in_real_time = True
def my_time_time(self):
return self.my_oldtime() + self.my_offset
def my_time_sleep(self, delay):
self.my_offset += delay
def time_warp(self, duration):
self.my_offset += duration
def set_my_time(self):
if self.in_real_time:
time.time = self.my_time_time
time.sleep = self.my_time_sleep
self.in_real_time = False
# If external processes or time stamps for files are involved, we must
# revert the fake timing routines, because these externals cannot be fooled.
# They get their times from the operating system.
def set_real_time(self):
if not self.in_real_time:
time.time = self.original_time_time
time.sleep = self.original_time_sleep
self.in_real_time = True
#Time hacking for every test!
time_hacker = TimeHacker()
time_hacker.set_my_time()
class Pluginconf(object):
pass
class ShinkenTest(unittest.TestCase):
def setUp(self):
self.setup_with_file('etc/shinken_1r_1h_1s.cfg')
def setup_with_file(self, path):
time_hacker.set_my_time()
self.print_header()
# i am arbiter-like
self.broks = []
self.me = None
self.log = logger
self.log.load_obj(self)
self.config_files = [path]
self.conf = Config()
buf = self.conf.read_config(self.config_files)
raw_objects = self.conf.read_config_buf(buf)
self.conf.create_objects_for_type(raw_objects, 'arbiter')
self.conf.create_objects_for_type(raw_objects, 'module')
self.conf.early_arbiter_linking()
# If we got one arbiter defined here (before default) we should be in a case where
# the tester want to load/test a module, so we simulate an arbiter daemon
# and the modules loading phase. As it has its own modulesmanager, should
# not impact scheduler modules ones, especially we are asking for arbiter type :)
if len(self.conf.arbiters) == 1:
arbdaemon = Arbiter([''],[''], False, False, None, None)
# only load if the module_dir is reallyexisting, so was set explicitly
# in the test configuration
if os.path.exists(getattr(self.conf, 'modules_dir', '')):
arbdaemon.modules_dir = self.conf.modules_dir
arbdaemon.load_modules_manager()
# we request the instances without them being *started*
# (for those that are concerned ("external" modules):
# we will *start* these instances after we have been daemonized (if requested)
for arb in self.conf.arbiters:
arbdaemon.modules_manager.set_modules(arb.modules)
arbdaemon.do_load_modules()
arbdaemon.load_modules_configuration_objects(raw_objects)
self.conf.create_objects(raw_objects)
self.conf.instance_id = 0
self.conf.instance_name = 'test'
# Hack push_flavor, that is set by the dispatcher
self.conf.push_flavor = 0
self.conf.load_triggers()
#import pdb;pdb.set_trace()
self.conf.linkify_templates()
#import pdb;pdb.set_trace()
self.conf.apply_inheritance()
#import pdb;pdb.set_trace()
self.conf.explode()
#print("Aconf.services has %d elements" % len(self.conf.services))
self.conf.apply_implicit_inheritance()
self.conf.fill_default()
self.conf.remove_templates()
self.conf.override_properties()
self.conf.linkify()
self.conf.apply_dependencies()
self.conf.set_initial_state()
self.conf.explode_global_conf()
self.conf.propagate_timezone_option()
self.conf.create_business_rules()
self.conf.create_business_rules_dependencies()
self.conf.is_correct()
if not self.conf.conf_is_correct:
print("The conf is not correct, I stop here")
self.conf.dump()
return
self.conf.clean()
self.confs = self.conf.cut_into_parts()
self.conf.prepare_for_sending()
self.conf.show_errors()
self.dispatcher = Dispatcher(self.conf, self.me)
scheddaemon = Shinken(None, False, False, False, None, None)
self.scheddaemon = scheddaemon
self.sched = scheddaemon.sched
scheddaemon.modules_dir = modules_dir
scheddaemon.load_modules_manager()
# Remember to clean the logs we just created before launching tests
self.clear_logs()
m = MacroResolver()
m.init(self.conf)
self.sched.load_conf(self.conf, in_test=True)
e = ExternalCommandManager(self.conf, 'applyer')
self.sched.external_command = e
e.load_scheduler(self.sched)
e2 = ExternalCommandManager(self.conf, 'dispatcher')
e2.load_arbiter(self)
self.external_command_dispatcher = e2
self.sched.conf.accept_passive_unknown_check_results = False
self.sched.schedule()
def add(self, b):
if isinstance(b, Brok):
self.broks.append(b)
return
if isinstance(b, ExternalCommand):
self.sched.run_external_command(b.cmd_line)
def fake_check(self, ref, exit_status, output="OK",
check_variant=SchedulingItem.default_check_variant,
fake_timeout=False):
#print("fake", ref)
now = time.time()
ref.schedule(force=True)
# now checks are schedule and we get them in
# the action queue
#check = ref.actions.pop()
check = ref.get_checks_in_progress(check_variant)[0]
self.sched.add(check) # check is now in sched.checks[]
# Allows to force check scheduling without setting its status nor
# output. Useful for manual business rules rescheduling, for instance.
if exit_status is None:
return
# fake execution
check.check_time = now
# and lie about when we will launch it because
# if not, the schedule call for ref
# will not really reschedule it because there
# is a valid value in the future
ref.next_chk = now - 0.5
check.get_outputs(output, 9000)
check.exit_status = exit_status
check.execution_time = 0.001
if fake_timeout is True:
check.status = "timeout"
else:
check.status = 'waitconsume'
self.sched.waiting_results.append(check)
def scheduler_loop(self, count, reflist, do_sleep=False, sleep_time=61,
verbose=True):
for ref in reflist:
if isinstance(ref, dict):
obj = ref["item"]
else:
obj = ref[0]
obj.checks_in_progress = []
for loop in range(1, count + 1):
if verbose is True:
print("processing check", loop)
for ref in reflist:
ext = {}
if isinstance(ref, dict):
obj = ref["item"]
exit_status = ref["exit_status"]
output = ref["output"]
if "check_variant" in ref:
ext["check_variant"] = ref["check_variant"]
if "timeout" in ref:
ext["fake_timeout"] = ref["timeout"]
else:
(obj, exit_status, output) = ref
self.fake_check(obj, exit_status, output, **ext)
self.sched.manage_internal_checks()
self.sched.consume_results()
self.sched.get_new_actions()
self.sched.get_new_broks()
self.sched.scatter_master_notifications()
self.worker_loop(verbose)
for ref in reflist:
if isinstance(ref, dict):
obj = ref["item"]
else:
obj = ref[0]
obj.checks_in_progress = []
self.sched.update_downtimes_and_comments()
#time.sleep(ref.retry_interval * 60 + 1)
if do_sleep:
time.sleep(sleep_time)
def worker_loop(self, verbose=True):
self.sched.delete_zombie_checks()
self.sched.delete_zombie_actions()
checks = self.sched.get_to_run_checks(True, False, worker_name='tester')
actions = self.sched.get_to_run_checks(False, True, worker_name='tester')
#print("------------ worker loop checks ----------------")
#print(checks)
#print("------------ worker loop actions ----------------")
if verbose is True:
self.show_actions()
#print("------------ worker loop new ----------------")
for a in actions:
a.status = 'inpoller'
a.check_time = time.time()
a.exit_status = 0
self.sched.put_results(a)
if verbose is True:
self.show_actions()
#print("------------ worker loop end ----------------")
def show_logs(self):
print("--- logs <<<----------------------------------")
if hasattr(self, "sched"):
broks = self.sched.broks
else:
broks = self.broks
for brok in broks:
if brok.type == 'log':
#brok.prepare()
safe_print("LOG: ", brok.data['log'])
print("--- logs >>>----------------------------------")
def show_actions(self):
print("--- actions <<<----------------------------------")
if hasattr(self, "sched"):
actions = self.sched.actions
else:
actions = self.actions
for a in sorted(actions.values(), key=lambda x: x.id):
if a.is_a == 'notification':
if a.ref.my_type == "host":
ref = "host: %s" % a.ref.get_name()
else:
ref = "host: %s svc: %s" % (a.ref.host.get_name(), a.ref.get_name())
print("NOTIFICATION %d %s %s %s %s" % (a.id, ref, a.type, time.asctime(time.localtime(a.t_to_go)), a.status))
elif a.is_a == 'eventhandler':
print("EVENTHANDLER:", a)
print("--- actions >>>----------------------------------")
def show_and_clear_logs(self):
self.show_logs()
self.clear_logs()
def show_and_clear_actions(self):
self.show_actions()
self.clear_actions()
def count_logs(self):
if hasattr(self, "sched"):
broks = self.sched.broks
else:
broks = self.broks
return len([b for b in broks if b.type == 'log'])
def count_actions(self):
if hasattr(self, "sched"):
actions = self.sched.actions
else:
actions = self.actions
return len(actions.values())
def clear_logs(self):
if hasattr(self, "sched"):
broks = self.sched.broks
else:
broks = self.broks
to_del = []
for b in broks:
if b.type == 'log':
to_del.append(b)
for b in to_del:
broks.remove(b)
def clear_actions(self):
if hasattr(self, "sched"):
self.sched.actions = {}
else:
self.actions = {}
def assert_log_match(self, index, pattern, no_match=False):
# log messages are counted 1...n, so index=1 for the first message
if not no_match:
self.assertGreaterEqual(self.count_logs(), index)
regex = re.compile(pattern)
lognum = 1
broks = sorted(self.sched.broks, key=lambda x: x.id)
for brok in broks:
if brok.type == 'log':
#brok.prepare()
print("%s (%s): %s" % (lognum, brok.id, brok.data['log']))
if index == lognum:
print(brok.data['log'])
if re.search(regex, brok.data['log']):
return
lognum += 1
#[b.prepare() for b in self.broks]
self.assertTrue(no_match, "%s found a matched log line in broks :\n"
"index=%s pattern=%r\n"
"broks_logs=[[[\n%s\n]]]" % (
'*HAVE*' if no_match else 'Not',
index, pattern, '\n'.join(
'\t%s=%s' % (idx, b.strip())
for idx, b in enumerate(
(b.data['log'] for b in self.broks if b.type == 'log'),
1)
)
))
def _any_log_match(self, pattern, assert_not):
regex = re.compile(pattern)
broks = getattr(self, 'sched', self).broks
broks = sorted(broks, key=lambda x: x.id)
for brok in broks:
if brok.type == 'log':
#brok.prepare()
if re.search(regex, brok.data['log']):
self.assertTrue(not assert_not,
"Found matching log line:\n"
"pattern = %r\nbrok log = %r" % (pattern, brok.data['log'])
)
return
self.assertTrue(assert_not,
"No matching log line found:\n"
"pattern = %r\n" "broks = %r" % (pattern, broks)
)
def assert_any_log_match(self, pattern):
self._any_log_match(pattern, assert_not=False)
def assert_no_log_match(self, pattern):
self._any_log_match(pattern, assert_not=True)
def get_log_match(self, pattern):
regex = re.compile(pattern)
res = []
for brok in self.sched.broks:
if brok.type == 'log':
if re.search(regex, brok.data['log']):
res.append(brok.data['log'])
return res
def print_header(self):
print("\n" + "#" * 80 + "\n" + "#" + " " * 78 + "#")
print("#" + str.center(self.id(), 78) + "#")
print("#" + " " * 78 + "#\n" + "#" * 80 + "\n")
def xtest_conf_is_correct(self):
self.print_header()
self.assertTrue(self.conf.conf_is_correct)
if __name__ == '__main__':
unittest.main()
| 18,888
|
Python
|
.py
| 450
| 32.204444
| 125
| 0.585186
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,329
|
test_freshness.py
|
shinken-solutions_shinken/test/test_freshness.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestFreshness(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_freshness.cfg')
# Check if the check_freshnes is doing it's job
def test_check_freshness(self):
self.print_header()
# We want an eventhandelr (the perfdata command) to be put in the actions dict
# after we got a service check
now = time.time()
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
svc.active_checks_enabled = False
self.assertEqual(True, svc.check_freshness)
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
# We do not want to be just a string but a real command
print("Additonal freshness latency", svc.__class__.additional_freshness_latency)
self.scheduler_loop(1, [[svc, 0, 'OK | bibi=99%']])
print("Addi:", svc.last_state_update, svc.freshness_threshold, svc.check_freshness)
# By default check fresh ness is set at false, so no new checks
self.assertEqual(0, len(svc.actions))
svc.do_check_freshness()
self.assertEqual(0, len(svc.actions))
# We make it 10s less than it was
svc.last_state_update = svc.last_state_update - 10
#svc.check_freshness = True
# Now we active it, with a too small value (now - 10s is still higer than now - (1 - 15, the addition time)
# So still no check
svc.freshness_threshold = 1
print("Addi:", svc.last_state_update, svc.freshness_threshold, svc.check_freshness)
svc.do_check_freshness()
self.assertEqual(0, len(svc.actions))
# Now active globaly the check freshness
cmd = "[%lu] ENABLE_SERVICE_FRESHNESS_CHECKS" % now
self.sched.run_external_command(cmd)
# Ok, now, we remove again 10s. Here we will saw the new entry
svc.last_state_update = svc.last_state_update - 10
svc.do_check_freshness()
self.assertEqual(1, len(svc.actions))
# And we check for the message in the log too
self.assert_any_log_match('The results of service.*')
if __name__ == '__main__':
unittest.main()
| 3,380
|
Python
|
.py
| 69
| 43.028986
| 115
| 0.659084
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,330
|
test_service_tpl_on_host_tpl.py
|
shinken-solutions_shinken/test/test_service_tpl_on_host_tpl.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestSrvTplOnHostTpl(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_service_tpl_on_host_tpl.cfg')
# Look is a service template apply on a host one will
# make hosts that inherit from it got such service
def test_service_tpl_on_host_tpl(self):
# In fact the whole thing will be to have the service defined :)
host = self.sched.hosts.find_by_name("test_host_0")
print("All the test_host_0 services")
for s in host.services:
print(s.get_dbg_name())
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "Service_Template_Description")
self.assertIsNot(svc, None)
# And look for multy layer template too. Like a service is apply on
# layer1, that use layer2. And srv is apply on layer2
def test_service_tpl_on_host_tpl_n_layers(self):
host = self.sched.hosts.find_by_name("host_multi_layers")
print("All the test_host_0 services")
for s in host.services:
print(s.get_dbg_name())
svc = self.sched.services.find_srv_by_name_and_hostname("host_multi_layers", "srv_multi_layer")
self.assertIsNot(svc, None)
# And look for multy layer template too. Like a service is apply on
# layer1, that use layer2. And srv is apply on layer2
def test_complex_expr(self):
h_linux = self.sched.hosts.find_by_name("host_linux_http")
print("All the host_linux_http services")
for s in h_linux.services:
print(s.get_dbg_name())
# The linux and http service should exist on the linux host
svc = self.sched.services.find_srv_by_name_and_hostname("host_linux_http", "http_AND_linux")
self.assertIsNot(svc, None)
# But not on the windows one
h_windows = self.sched.hosts.find_by_name("host_windows_http")
print("All the host_windows_http services")
for s in h_windows.services:
print(s.get_dbg_name())
# The linux and http service should exist on the linux host
svc = self.sched.services.find_srv_by_name_and_hostname("host_windows_http", "http_AND_linux")
self.assertIs(None, svc)
# The http_OR_linux should be every where
svc = self.sched.services.find_srv_by_name_and_hostname("host_linux_http", "http_OR_linux")
self.assertIsNot(svc, None)
svc = self.sched.services.find_srv_by_name_and_hostname("host_windows_http", "http_OR_linux")
self.assertIsNot(svc, None)
# The http_BUT_NOT_linux should be in the windows host only
svc = self.sched.services.find_srv_by_name_and_hostname("host_linux_http", "http_BUT_NOT_linux")
self.assertIs(None, svc)
svc = self.sched.services.find_srv_by_name_and_hostname("host_windows_http", "http_BUT_NOT_linux")
self.assertIsNot(svc, None)
# The http_ALL_BUT_NOT_linux should be in the windows host only
svc = self.sched.services.find_srv_by_name_and_hostname("host_linux_http", "http_ALL_BUT_NOT_linux")
self.assertIs(None, svc)
svc = self.sched.services.find_srv_by_name_and_hostname("host_windows_http", "http_ALL_BUT_NOT_linux")
self.assertIsNot(svc, None)
# The http_ALL_BUT_NOT_linux_AND_EVEN_LINUX should be every where :)
# yes, it's a stupid example, but at least it help to test :)
svc = self.sched.services.find_srv_by_name_and_hostname("host_linux_http", "http_ALL_BUT_NOT_linux_AND_EVEN_LINUX")
self.assertIsNot(svc, None)
svc = self.sched.services.find_srv_by_name_and_hostname("host_windows_http", "http_ALL_BUT_NOT_linux_AND_EVEN_LINUX")
self.assertIsNot(svc, None)
if __name__ == '__main__':
unittest.main()
| 4,743
|
Python
|
.py
| 87
| 47.965517
| 125
| 0.689834
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,331
|
test_conf_in_symlinks.py
|
shinken-solutions_shinken/test/test_conf_in_symlinks.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sys
from shinken_test import *
class TestConfigWithSymlinks(ShinkenTest):
def setUp(self):
if os.name == 'nt':
return
self.setup_with_file('etc/shinken_conf_in_symlinks.cfg')
def test_symlinks(self):
if os.name == 'nt':
return
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_HIDDEN")
self.assertIsNot(svc, None)
if __name__ == '__main__':
unittest.main()
| 1,449
|
Python
|
.py
| 38
| 34.894737
| 93
| 0.726106
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,332
|
test_flapping.py
|
shinken-solutions_shinken/test/test_flapping.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestFlapping(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_flapping.cfg')
def test_flapping(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
router = self.sched.hosts.find_by_name("test_router_0")
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [router, 0, 'UP | rtt=10'], [svc, 0, 'OK']])
self.assertEqual('UP', host.state)
self.assertEqual('HARD', host.state_type)
self.assertTrue(svc.flap_detection_enabled)
print('A' * 41, svc.low_flap_threshold)
self.assertEqual(-1, svc.low_flap_threshold)
# Now 1 test with a bad state
self.scheduler_loop(1, [[svc, 2, 'Crit']])
print("******* Current flap change lsit", svc.flapping_changes)
self.scheduler_loop(1, [[svc, 2, 'Crit']])
print("****** Current flap change lsit", svc.flapping_changes)
# Ok, now go in flap!
for i in range(1, 10):
"**************************************************"
print("I:", i)
self.scheduler_loop(1, [[svc, 0, 'Ok']])
print("******* Current flap change lsit", svc.flapping_changes)
self.scheduler_loop(1, [[svc, 2, 'Crit']])
print("****** Current flap change lsit", svc.flapping_changes)
print("In flapping?", svc.is_flapping)
# Should get in flapping now
self.assertTrue(svc.is_flapping)
# and get a log about it
self.assert_any_log_match('SERVICE FLAPPING ALERT.*;STARTED')
self.assert_any_log_match('SERVICE NOTIFICATION.*;FLAPPINGSTART')
# Now we put it as back :)
# 10 is not enouth to get back as normal
for i in range(1, 11):
self.scheduler_loop(1, [[svc, 0, 'Ok']])
print("In flapping?", svc.is_flapping)
self.assertTrue(svc.is_flapping)
# 10 others can be good (near 4.1 %)
for i in range(1, 11):
self.scheduler_loop(1, [[svc, 0, 'Ok']])
print("In flapping?", svc.is_flapping)
self.assertFalse(svc.is_flapping)
self.assert_any_log_match('SERVICE FLAPPING ALERT.*;STOPPED')
self.assert_any_log_match('SERVICE NOTIFICATION.*;FLAPPINGSTOP')
############ Now get back in flap, and try the exteral commands change
# Now 1 test with a bad state
self.scheduler_loop(1, [[svc, 2, 'Crit']])
print("******* Current flap change lsit", svc.flapping_changes)
self.scheduler_loop(1, [[svc, 2, 'Crit']])
print("****** Current flap change lsit", svc.flapping_changes)
# Ok, now go in flap!
for i in range(1, 10):
"**************************************************"
print("I:", i)
self.scheduler_loop(1, [[svc, 0, 'Ok']])
print("******* Current flap change lsit", svc.flapping_changes)
self.scheduler_loop(1, [[svc, 2, 'Crit']])
print("****** Current flap change lsit", svc.flapping_changes)
print("In flapping?", svc.is_flapping)
# Should get in flapping now
self.assertTrue(svc.is_flapping)
# and get a log about it
self.assert_any_log_match('SERVICE FLAPPING ALERT.*;STARTED')
self.assert_any_log_match('SERVICE NOTIFICATION.*;FLAPPINGSTART')
# We run a globa lflap disable, so we should stop flapping now
cmd = "[%lu] DISABLE_FLAP_DETECTION" % int(time.time())
self.sched.run_external_command(cmd)
self.assertFalse(svc.is_flapping)
############# NOW a local command for this service
# First reenable flap:p
cmd = "[%lu] ENABLE_FLAP_DETECTION" % int(time.time())
self.sched.run_external_command(cmd)
# Now 1 test with a bad state
self.scheduler_loop(1, [[svc, 2, 'Crit']])
print("******* Current flap change lsit", svc.flapping_changes)
self.scheduler_loop(1, [[svc, 2, 'Crit']])
print("****** Current flap change lsit", svc.flapping_changes)
# Ok, now go in flap!
for i in range(1, 10):
"**************************************************"
print("I:", i)
self.scheduler_loop(1, [[svc, 0, 'Ok']])
print("******* Current flap change lsit", svc.flapping_changes)
self.scheduler_loop(1, [[svc, 2, 'Crit']])
print("****** Current flap change lsit", svc.flapping_changes)
print("In flapping?", svc.is_flapping)
# Should get in flapping now
self.assertTrue(svc.is_flapping)
# and get a log about it
self.assert_any_log_match('SERVICE FLAPPING ALERT.*;STARTED')
self.assert_any_log_match('SERVICE NOTIFICATION.*;FLAPPINGSTART')
# We run a globa lflap disable, so we should stop flapping now
cmd = "[%lu] DISABLE_SVC_FLAP_DETECTION;test_host_0;test_ok_0" % int(time.time())
self.sched.run_external_command(cmd)
self.assertFalse(svc.is_flapping)
if __name__ == '__main__':
unittest.main()
| 6,344
|
Python
|
.py
| 128
| 41.296875
| 113
| 0.601939
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,333
|
test_bad_escalation_on_groups.py
|
shinken-solutions_shinken/test/test_bad_escalation_on_groups.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestBadEscaOnGroups(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_bad_escalation_on_groups.cfg')
def test_escalation_inheritance(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
print(svc.escalations)
self.assertGreater(len(svc.escalations), 0)
es = svc.escalations.pop()
self.assertTrue(es.is_correct())
if __name__ == '__main__':
unittest.main()
| 2,081
|
Python
|
.py
| 49
| 37.755102
| 91
| 0.697329
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,334
|
test_module_as_package.py
|
shinken-solutions_shinken/test/test_module_as_package.py
|
from __future__ import absolute_import, division, print_function, unicode_literals
from os.path import abspath, dirname, join
from shinken_test import unittest, ShinkenTest
from shinken.objects.module import Module
from shinken.modulesmanager import ModulesManager
modules_dir = join(dirname(abspath(__file__)), 'test_module_as_package')
class TestModuleManager_And_Packages(ShinkenTest):
''' Test to make sure that we correctly import shinken modules.
'''
def test_conflicting_modules(self):
# prepare 2 modconfs:
modconfA = Module({'module_name': 'whatever', 'module_type': 'modA'})
modconfB = Module({'module_name': '42', 'module_type': 'modB'})
mods = (modconfA, modconfB)
mm = self.modulemanager = ModulesManager('broker', modules_dir, mods)
mm.load_and_init()
for mod in mm.imported_modules:
self.assertEqual(mod.expected_helpers_X, mod.helpers_X)
mod1, mod2 = mm.imported_modules
self.assertNotEqual(mod1.helpers_X, mod2.helpers_X)
if __name__ == '__main__':
unittest.main()
| 1,104
|
Python
|
.py
| 22
| 43.909091
| 82
| 0.695122
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,335
|
test_bad_timeperiods.py
|
shinken-solutions_shinken/test/test_bad_timeperiods.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_bad_timeperiods.cfg')
def test_bad_timeperiod(self):
print("Get the bad timeperiod")
tp = self.conf.timeperiods.find_by_name("24x7")
self.assertEqual(True, tp.is_correct())
tp = self.conf.timeperiods.find_by_name("24x7_bad")
self.assertEqual(False, tp.is_correct())
if __name__ == '__main__':
unittest.main()
| 1,450
|
Python
|
.py
| 35
| 38.457143
| 82
| 0.736131
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,336
|
test_bad_start.py
|
shinken-solutions_shinken/test/test_bad_start.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import tempfile
import shutil
from shinken_test import *
import shinken.log as shinken_log
from shinken.daemon import InvalidPidFile, InvalidWorkDir
from shinken.http_daemon import PortNotFree
from shinken.daemons.pollerdaemon import Poller
from shinken.daemons.brokerdaemon import Broker
from shinken.daemons.schedulerdaemon import Shinken
from shinken.daemons.reactionnerdaemon import Reactionner
from shinken.daemons.arbiterdaemon import Arbiter
try:
import pwd, grp
from pwd import getpwnam
from grp import getgrnam
def get_cur_user():
return pwd.getpwuid(os.getuid()).pw_name
def get_cur_group():
return grp.getgrgid(os.getgid()).gr_name
except ImportError as exp: # Like in nt system or Android
# temporary workaround:
def get_cur_user():
return os.getlogin()
def get_cur_group():
return os.getlogin()
curdir = os.getcwd()
daemons_config = {
Broker: "etc/core/daemons/brokerd.ini",
Poller: "etc/core/daemons/pollerd.ini",
Reactionner: "etc/core/daemons/reactionnerd.ini",
Shinken: "etc/core/daemons/schedulerd.ini",
Arbiter: ["etc/core/shinken.cfg"]
}
import random
HIGH_PORT = random.randint(30000,65000)
run = 0 # We will open some ports but not close them (yes it's not good) and
# so we will open a range from a high port
class template_Daemon_Bad_Start():
def setUp(self):
time_hacker.set_real_time()
def get_login_and_group(self, p):
try:
p.user = get_cur_user()
p.group = get_cur_group()
except OSError: # on some rare case, we can have a problem here
# so bypass it and keep default value
return
def create_daemon(self):
cls = self.daemon_cls
return cls(daemons_config[cls], False, True, False, None, '')
def get_daemon(self):
global run
os.chdir(curdir)
shinken_log.local_log = None # otherwise get some "trashs" logs..
d = self.create_daemon()
d.load_config_file()
d.http_backend = 'wsgiref'
d.port = HIGH_PORT + run # random high port, I hope no one is using it :)
run += 1
self.get_login_and_group(d)
return d
def test_bad_piddir(self):
print("Testing bad pidfile ...")
d = self.get_daemon()
d.workdir = tempfile.mkdtemp()
d.pidfile = os.path.join('/proc/DONOTEXISTS', "daemon.pid")
prev_dir = os.getcwd()
self.assertRaises(InvalidPidFile, d.do_daemon_init_and_start, fake=True)
shutil.rmtree(d.workdir)
os.chdir(prev_dir)
def test_bad_workdir(self):
print("Testing bad workdir ... mypid=%d" % (os.getpid()))
d = self.get_daemon()
d.workdir = '/proc/DONOTEXISTS'
prev_dir = os.getcwd()
self.assertRaises(InvalidWorkDir, d.do_daemon_init_and_start, fake=True)
d.do_stop()
os.chdir(prev_dir)
def _test_port_not_free(self):
print("Testing port not free ... mypid=%d" % (os.getpid()))
d1 = self.get_daemon()
d1.workdir = tempfile.mkdtemp()
prev_dir = os.getcwd() # We have to remember where we are to get back after
d1.do_daemon_init_and_start(fake=True)
new_dir = os.getcwd() # We have to remember this one also
os.chdir(prev_dir)
os.unlink(os.path.join(new_dir, d1.pidfile)) ## so that second poller will not see first started poller
d2 = self.get_daemon()
d2.workdir = d1.workdir
# TODO: find a way in Pyro4 to get the port
if hasattr(d1.http_daemon, 'port'):
d2.port = d1.http_daemon.port
d2.do_daemon_init_and_start(fake=True)
#self.assertRaises(PortNotFree, d2.do_daemon_init_and_start, fake=True)
d2.do_stop()
d1.do_stop()
try:
os.unlink(d1.pidfile)
except Exception:
pass
if hasattr(d1, 'local_log'):
os.unlink(os.path.join(d1.workdir, d1.local_log))
shutil.rmtree(d1.workdir)
os.chdir(prev_dir) # Back to previous dir for next test!
class Test_Broker_Bad_Start(template_Daemon_Bad_Start, ShinkenTest):
daemon_cls = Broker
class Test_Scheduler_Bad_Start(template_Daemon_Bad_Start, ShinkenTest):
daemon_cls = Shinken
class Test_Poller_Bad_Start(template_Daemon_Bad_Start, ShinkenTest):
daemon_cls = Poller
class Test_Reactionner_Bad_Start(template_Daemon_Bad_Start, ShinkenTest):
daemon_cls = Reactionner
class Test_Arbiter_Bad_Start(template_Daemon_Bad_Start, ShinkenTest):
daemon_cls = Arbiter
def create_daemon(self):
""" arbiter is always a bit special .. """
cls = self.daemon_cls
#Arbiter(config_files, is_daemon, do_replace, verify_only, debug, debug_file, profile)
return cls(daemons_config[cls], False, True, False, False, None, '')
if __name__ == '__main__':
unittest.main()
| 5,938
|
Python
|
.py
| 145
| 34.931034
| 112
| 0.674605
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,337
|
test_service_nohost.py
|
shinken-solutions_shinken/test/test_service_nohost.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestServiceNoHost(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_service_nohost.cfg')
def test_service_with_no_host(self):
# A service that has no host to be linked to should raise on error.
self.assertIs(False, self.conf.conf_is_correct)
#[b.prepare() for b in self.broks]
logs = [b.data['log'] for b in self.broks if b.type == 'log']
self.assertLess(
0,
len( [ log
for log in logs
if re.search(
'a service has been defined without host_name nor hostgroups ',
log)
])
)
if __name__ == '__main__':
unittest.main()
| 1,755
|
Python
|
.py
| 43
| 34.534884
| 95
| 0.665491
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,338
|
test_css_in_command.py
|
shinken-solutions_shinken/test/test_css_in_command.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestCssInCommands(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_css_in_command.cfg')
def test_dummy(self):
r = self.conf.conf_is_correct
self.assertTrue(r)
print(r)
if __name__ == '__main__':
unittest.main()
| 1,276
|
Python
|
.py
| 33
| 36.060606
| 82
| 0.743112
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,339
|
test_hostdep_withno_depname.py
|
shinken-solutions_shinken/test/test_hostdep_withno_depname.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestHostDepWithNodepname(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_hostdep_withno_depname.cfg')
def test_hostdep_withno_depname(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
h2 = self.sched.hosts.find_by_name("test_host_1")
self.assertIsNot(h2, None)
# Should got a link between host and h2
print(h2.act_depend_of)
self.assertGreater(len(h2.act_depend_of), 0)
l = h2.act_depend_of[0]
h = l[0] # the host that h2 depend on
self.assertIs(host, h)
if __name__ == '__main__':
unittest.main()
| 1,810
|
Python
|
.py
| 45
| 35.933333
| 82
| 0.704041
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,340
|
test_illegal_names.py
|
shinken-solutions_shinken/test/test_illegal_names.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
# setUp is inherited from ShinkenTest
def test_illegal_caracter_in_names(self):
illegal_caracts = self.sched.conf.illegal_object_name_chars
print("Illegal caracters: %s" % illegal_caracts)
host = self.sched.hosts.find_by_name("test_host_0")
# should be correct
self.assertTrue(host.is_correct())
# Now change the name with incorrect caract
for c in illegal_caracts:
host.host_name = 'test_host_0' + c
# and Now I want an incorrect here
self.assertEqual(False, host.is_correct())
if __name__ == '__main__':
unittest.main()
| 1,655
|
Python
|
.py
| 39
| 38.564103
| 82
| 0.722015
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,341
|
test_arbiterlink_errors.py
|
shinken-solutions_shinken/test/test_arbiterlink_errors.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Sebastien Coavoux, s.coavoux@free.fr
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestArbiterError(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_1r_1h_1s.cfg')
def test_arbiter_error(self):
arbiterlink = self.conf.arbiters.find_by_name('Default-Arbiter')
self.assertListEqual(arbiterlink.configuration_errors, [])
if __name__ == '__main__':
unittest.main()
| 1,293
|
Python
|
.py
| 31
| 39.258065
| 82
| 0.752594
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,342
|
test_service_on_missing_template.py
|
shinken-solutions_shinken/test/test_service_on_missing_template.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestSrvOnMissingTemplate(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_service_on_missing_template.cfg')
def test_missing_template(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_2", "ZE-SERVICE")
self.assertIsNot(svc, None)
if __name__ == '__main__':
unittest.main()
| 1,474
|
Python
|
.py
| 36
| 37.777778
| 92
| 0.735994
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,343
|
test_logging.py
|
shinken-solutions_shinken/test/test_logging.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012:
# Hartmut Goebel <h.goebel@crazy-compilers.com>
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
"""
Test shinken.logging
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import six
import sys
import os
import time
from io import StringIO
from tempfile import NamedTemporaryFile
import __import_shinken
import logging
from logging import NOTSET, DEBUG, INFO, WARNING, ERROR, CRITICAL, StreamHandler
from shinken.log import logger as shinken_logger, naglog_result, Log, human_timestamp_log
from shinken.log import defaultFormatter, BrokHandler, ColorStreamHandler
shinken_logger.set_log = True
from shinken.brok import Brok
from shinken_test import *
# The logging module requires some object for collecting broks
class Dummy:
"""Dummy class for collecting broks"""
def add(self, o):
pass
class Collector:
"""Dummy class for collecting broks"""
def __init__(self):
self.list = []
def add(self, o):
self.list.append(o)
class NoSetup:
def setUp(self):
pass
#logger.load_obj(Dummy())
class TestLevels(NoSetup, ShinkenTest):
def test_default_level(self):
logger = Log(name=None, log_set=True)
self.assertEqual(logger.level, logging.NOTSET)
def test_setLevel(self):
logger = Log(name=None, log_set=True)
logger.setLevel(logging.WARNING)
self.assertEqual(logger.level, min(WARNING, INFO))
def test_setLevel_non_integer_raises(self):
logger = Log(name=None, log_set=True)
self.assertRaises(TypeError, logger.setLevel, 1.0)
def test_load_obj_must_not_change_level(self):
logger = Log(name=None, log_set=True)
# argl, load_obj() unsets the level! save and restore it
logger.setLevel(logging.CRITICAL)
logger.load_obj(Dummy())
self.assertEqual(logger.level, min(CRITICAL, INFO))
class TestBasics(NoSetup, ShinkenTest):
def test_setting_and_unsetting_human_timestamp_format(self):
# :hack: shinken.log.human_timestamp_log is a global variable
self.assertEqual(shinken.log.human_timestamp_log, False)
logger.set_human_format(True)
self.assertEqual(shinken.log.human_timestamp_log, True)
logger.set_human_format(False)
self.assertEqual(shinken.log.human_timestamp_log, False)
logger.set_human_format(True)
self.assertEqual(shinken.log.human_timestamp_log, True)
logger.set_human_format(False)
self.assertEqual(shinken.log.human_timestamp_log, False)
class LogCollectMixin:
def _get_brok_log_messages(self, collector):
"""
Return the log messages stored as Broks into the collector.
This also tests whether all objects collected by the collector
are log entries.
"""
for obj in collector.list:
self.assertIsInstance(obj, Brok)
self.assertEqual(obj.type, 'log')
self.assertEqual(list(obj.data.keys()), ['log'])
yield obj.data['log']
def _prepare_logging(self):
self._collector = Collector()
self._stdout = sys.stdout
sys.stdout = StringIO()
logger = Log(name=None, log_set=True)
sh = StreamHandler(sys.stdout)
sh.setFormatter(defaultFormatter)
logger.addHandler(sh)
logger.load_obj(self._collector)
logger.pre_log_buffer = [] # reset the pre_log for several tests
return logger
def _get_logging_output(self):
broklogs = list(self._get_brok_log_messages(self._collector))
stdoutlogs = sys.stdout.getvalue().splitlines()
sys.stdout = sys.__stdout__
if hasattr(self, 'logfile_name'):
with open(self.logfile_name, "r") as f:
filelogs = list(f.readlines())
try:
os.remove(self.logfile_name)
except Exception: # On windows, the file is still lock. But should be close!?!
pass
else:
filelogs = None
return broklogs, stdoutlogs, filelogs
def _put_log(self, log_method, *messages):
#self._prepare_logging()
try:
for msg in messages:
log_method(msg)
finally:
return self._get_logging_output()
def generic_tst(self, fun, msg, lenlist, patterns):
#sys.stdout = StringIO()
loglist = self._put_log(fun, msg)
for i, length in enumerate(lenlist):
self.assertEqual(len(loglist[i]), length)
if length != 0 and patterns[i]:
if six.PY2:
self.assertRegexpMatches(loglist[i][0], patterns[i])
else:
self.assertRegex(loglist[i][0], patterns[i])
return loglist
class TestDefaultLoggingMethods(NoSetup, ShinkenTest, LogCollectMixin):
def test_basic_logging_log(self):
sys.stdout = StringIO()
self._collector = Collector()
sh = StreamHandler(sys.stdout)
sh.setFormatter(defaultFormatter)
shinken_logger.handlers = []
shinken_logger.addHandler(sh)
shinken_logger.load_obj(self._collector)
shinken_logger.log_set = True
shinken_logger.setLevel(DEBUG)
self.generic_tst(lambda x: naglog_result('info', x), 'Some log-message',
[1, 1], [r'^\[\d+\] Some log-message\n$', r'^\[\d+\] Some log-message$'])
def test_basic_logging_debug_does_not_send_broks(self):
logger = self._prepare_logging()
logger.setLevel(DEBUG)
self.generic_tst(logger.debug, 'Some log-message',
[0, 1], ['', r'^\[\d+\] DEBUG:\s+Some log-message$'])
def test_basic_logging_info(self):
logger = self._prepare_logging()
logger.setLevel(INFO)
self.generic_tst(logger.info, 'Some log-message',
[1, 1], [r'^\[\d+\] INFO:\s+Some log-message\n$', r'^\[\d+\] INFO:\s+Some log-message$'])
def test_basic_logging_warning(self):
logger = self._prepare_logging()
logger.setLevel(WARNING)
self.generic_tst(logger.warning, 'Some log-message',
[1, 1], [r'^\[\d+\] WARNING:\s+Some log-message\n$', r'^\[\d+\] WARNING:\s+Some log-message$'])
def test_basic_logging_error(self):
logger = self._prepare_logging()
logger.setLevel(ERROR)
self.generic_tst(logger.error, 'Some log-message',
[1, 1], [r'^\[\d+\] ERROR:\s+Some log-message\n$', r'^\[\d+\] ERROR:\s+Some log-message$'])
def test_basic_logging_critical(self):
logger = self._prepare_logging()
logger.setLevel(CRITICAL)
self.generic_tst(logger.critical, 'Some log-message',
[1, 1],
[r'^\[\d+\] CRITICAL:\s+Some log-message\n$', r'^\[\d+\] CRITICAL:\s+Some log-message$'])
def test_level_is_higher_then_the_one_set(self):
logger = self._prepare_logging()
# just test two samples
logger.setLevel(CRITICAL)
self.generic_tst(logger.error, 'Some log-message',
[1, 0], [r'^\[\d+\] ERROR:\s+Some log-message\n$', ''])
# need to prepare again to have stdout=StringIO()
logger = self._prepare_logging()
logger.setLevel(logging.INFO)
self.generic_tst(logger.debug, 'Some log-message',
[0, 0], ['', ''])
def test_human_timestamp_format(self):
"test output using the human timestamp format"
logger = self._prepare_logging()
logger.setLevel(logging.INFO)
logger.set_human_format(True)
loglist = self.generic_tst(logger.info, 'Some ] log-message',
[1, 1], [r'^\[\d+\] INFO:\s+Some \] log-message\n$', r'^\[[^\]]+] INFO:\s+Some \] log-message$'])
time.strptime(loglist[1][0].split(' INFO: ', 1)[0], '[%a %b %d %H:%M:%S %Y]')
logger.set_human_format(False)
def test_reset_human_timestamp_format(self):
"test output after switching of the human timestamp format"
# ensure the human timestamp format is set, ...
self.test_human_timestamp_format()
# ... then turn it off
logger.set_human_format(False)
# test whether the normal format is used again
self.test_basic_logging_info()
class TestColorConsoleLogger(NoSetup, ShinkenTest, LogCollectMixin):
def test_basic_logging_info_colored(self):
shinken_logger.setLevel(INFO)
self._collector = Collector()
sys.stdout = StringIO()
shinken_logger.handlers[0].stream = sys.stdout
shinken_logger.load_obj(self._collector)
if isinstance(shinken_logger.handlers[0], ColorStreamHandler):
self.generic_tst(shinken_logger.info, 'Some log-message',
[1, 1],
[r'^\[.+?\] INFO: \[Shinken\] Some log-message$',
r'^\x1b\[95m\[.+?\] INFO: \[Shinken\] Some log-message\x1b\[0m$'])
else:
self.generic_tst(shinken_logger.info, 'Some log-message',
[1, 1],
[r'^\[.+?\] INFO:\s+Some log-message$',
r'^\[.+?\] INFO:\s+Some log-message$'])
sys.stdout.close()
def test_human_timestamp_format(self):
"test output using the human timestamp format"
shinken_logger.setLevel(INFO)
self._collector = Collector()
sys.stdout = StringIO()
shinken_logger.handlers[0].stream = sys.stdout
shinken_logger.load_obj(self._collector)
shinken_logger.set_human_format(True)
if isinstance(shinken_logger.handlers[0], ColorStreamHandler):
loglist = self.generic_tst(shinken_logger.info, 'Some log-message',
[1, 1],
[r'^\[.+?\] INFO: \[Shinken\] Some log-message$',
r'^\x1b\[95m\[.+?\] INFO: \[Shinken\] Some log-message\x1b\[0m$'])
else:
loglist = self.generic_tst(shinken_logger.info, 'Some log-message',
[1, 1],
[r'^\[.+?\] INFO: \[Shinken\] Some log-message$',
r'^\[.+?\] INFO: \[Shinken\] Some log-message$'])
times = loglist[1][0].split(' INFO: ', 1)[0]
_, time2 = times.rsplit('[', 1)
time.strptime(time2.rsplit(']')[0], '%a %b %d %H:%M:%S %Y')
logger.set_human_format(False)
sys.stdout.close()
def test_reset_human_timestamp_format(self):
"test output after switching of the human timestamp format"
# ensure the human timestamp format is set, ...
self.test_human_timestamp_format()
# ... then turn it off
logger.set_human_format(False)
# test whether the normal format is used again
self.test_basic_logging_info_colored()
class TestWithLocalLogging(NoSetup, ShinkenTest, LogCollectMixin):
def _prepare_logging(self):
logger = super(TestWithLocalLogging, self)._prepare_logging()
# set up a temporary file for logging
logfile = NamedTemporaryFile("w", delete=False)
logfile.close()
self.logfile_name = logfile.name
logger.register_local_log(logfile.name, purge_buffer=False)
return logger
def test_register_local_log_keeps_level(self):
logger = self._prepare_logging()
logger.setLevel(ERROR)
self.assertEqual(logger.level, min(ERROR, INFO))
for handler in logger.handlers:
if isinstance(handler, Collector) or isinstance(handler, BrokHandler):
self.assertEqual(handler.level, INFO)
else:
self.assertEqual(handler.level, ERROR)
logfile = NamedTemporaryFile("w", delete=False)
logfile.close()
logfile_name = logfile.name
logger.register_local_log(logfile_name, purge_buffer=False)
self.assertEqual(logger.level, min(ERROR, INFO))
def test_basic_logging_log(self):
sys.stdout = StringIO()
self._collector = Collector()
sh = StreamHandler(sys.stdout)
sh.setFormatter(defaultFormatter)
shinken_logger.handlers = []
shinken_logger.addHandler(sh)
shinken_logger.load_obj(self._collector)
shinken_logger.log_set = True
logfile = NamedTemporaryFile("w", delete=False)
logfile.close()
self.logfile_name = logfile.name
shinken_logger.register_local_log(logfile.name, purge_buffer=False)
shinken_logger.setLevel(DEBUG)
self.generic_tst(lambda x: naglog_result('info', x), 'Some log-message',
[1, 1, 1], ['', r'^\[\d+\] Some log-message$', r'^\[\d+\] Some log-message$'])
sys.stdout.close()
def test_basic_logging_debug_does_not_send_broks(self):
logger = self._prepare_logging()
logger.setLevel(DEBUG)
self.generic_tst(logger.debug, 'Some log-message',
[0, 1, 1], ['', '', r'\[\d+\] DEBUG:\s+Some log-message$'])
def test_basic_logging_info(self):
logger = self._prepare_logging()
logger.setLevel(INFO)
self.generic_tst(logger.info, 'Some log-message',
[1, 1, 1], ['', '', r'\[\d+\] INFO:\s+Some log-message\n$'])
def test_basic_logging_error(self):
logger = self._prepare_logging()
logger.setLevel(ERROR)
self.generic_tst(logger.error, 'Some log-message',
[1, 1, 1], ['', '', r'\[\d+\] ERROR:\s+Some log-message\n$'])
def test_basic_logging_critical(self):
logger = self._prepare_logging()
logger.setLevel(CRITICAL)
self.generic_tst(logger.critical, 'Some log-message',
[1, 1, 1], ['', '', r'\[\d+\] CRITICAL:\s+Some log-message\n$'])
def test_level_is_higher_then_the_one_set(self):
logger = self._prepare_logging()
# just test two samples
logger.setLevel(CRITICAL)
self.generic_tst(logger.debug, 'Some log-message', [0, 0, 0], ['', '', ''])
# need to prepare again to have stdout=StringIO() and a local log file
logger = self._prepare_logging()
logger.setLevel(INFO)
self.generic_tst(logger.debug, 'Some log-message', [0, 0, 0], ['', '', ''])
def test_human_timestamp_format(self):
logger = self._prepare_logging()
logger.setLevel(logging.INFO)
logger.set_human_format(True)
loglist = self.generic_tst(logger.info, 'Some log-message',
[1, 1, 1],
[r'', r'', r'\[[^\]]+] INFO:\s+Some log-message\n$'])
# :fixme: Currently, the local log gets prefixed another
# timestamp. As it is yet unclear, whether this intended or
# not, we test it, too.
times = loglist[2][0].split(' INFO: ', 1)[0]
_, time2 = times.rsplit('[', 1)
time.strptime(time2.rsplit(']')[0], '%a %b %d %H:%M:%S %Y')
logger.set_human_format(False)
def test_reset_human_timestamp_format(self):
"test output after switching of the human timestamp format"
# ensure the human timestamp format is set, ...
self.test_human_timestamp_format()
# ... then turn it off
logger.set_human_format(False)
# test whether the normal format is used again
self.test_basic_logging_info()
class TestNamedCollector(NoSetup, ShinkenTest, LogCollectMixin):
# :todo: add a test for the local log file, too
def _prepare_logging(self):
self._collector = Collector()
self._stdout = sys.stdout
sys.stdout = StringIO()
logger = Log(name=None, log_set=True)
from shinken.log import defaultFormatter
from logging import StreamHandler
sh = StreamHandler(sys.stdout)
sh.setFormatter(defaultFormatter)
logger.addHandler(sh)
logger.load_obj(self._collector, 'Tiroler Schinken')
return logger
def test_basic_logging_info(self):
logger = self._prepare_logging()
logger.setLevel(logging.INFO)
self.generic_tst(logger.info, 'Some log-message',
[1, 1],
[r'^\[\d+\] INFO:\s+\[Tiroler Schinken\] Some log-message\n$',
r'^\[\d+\] INFO:\s+\[Tiroler Schinken\] Some log-message$'])
sys.stdout.close()
def test_human_timestamp_format(self):
logger = self._prepare_logging()
logger.setLevel(logging.INFO)
logger.set_human_format(True)
loglist = self.generic_tst(logger.info, 'Some ] log-message',
[1, 1],
[r'^\[\d+\] INFO:\s+\[Tiroler Schinken\] Some \] log-message\n$',
r'^\[[^\]]+] INFO:\s+\[Tiroler Schinken\] Some \] log-message$'])
# No TS for broker!
time.strptime(loglist[1][0].split(' INFO: ', 1)[0], '[%a %b %d %H:%M:%S %Y]')
logger.set_human_format(False)
sys.stdout.close()
def test_reset_human_timestamp_format(self):
# ensure human timestamp format is set and working
self.test_human_timestamp_format()
# turn of human timestamp format
logger.set_human_format(False)
# test for normal format
self.test_basic_logging_info()
if __name__ == '__main__':
unittest.main()
| 18,180
|
Python
|
.py
| 387
| 37.165375
| 122
| 0.60749
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,344
|
test_eventids.py
|
shinken-solutions_shinken/test/test_eventids.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test current_event_id, last_event_id,
# current_problem_id and last_problem_id which are used for
# $HOSTEVENTID$, $HOSTPROBLEMID$ etc.
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
from shinken.objects.schedulingitem import SchedulingItem
class TestConfig(ShinkenTest):
def print_ids(self, host, svc, router):
print("global: cei,lei,cpi,lpi = %d,%d" % (SchedulingItem.current_event_id, SchedulingItem.current_problem_id))
print("service: cei,lei,cpi,lpi = %d,%d,%d,%d" % (svc.current_event_id, svc.last_event_id, svc.current_problem_id, svc.last_problem_id))
print("host: cei,lei,cpi,lpi = %d,%d,%d,%d" % (host.current_event_id, host.last_event_id, host.current_problem_id, host.last_problem_id))
print("router: cei,lei,cpi,lpi = %d,%d,%d,%d" % (router.current_event_id, router.last_event_id, router.current_problem_id, router.last_problem_id))
def test_global_counters(self):
self.print_header()
# retry_interval 2
# critical notification
# run loop -> another notification
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
# This may be truc when running all Shinken test in the same "context" like
# nosetest does. If you run this test alone, it will be 0.
if SchedulingItem.current_event_id > 0 or SchedulingItem.current_problem_id > 0:
SchedulingItem.current_event_id = 0
SchedulingItem.current_problem_id = 0
self.print_ids(host, svc, router)
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']], do_sleep=False)
print("- 1 x OK -------------------------------------")
self.scheduler_loop(1, [[svc, 0, 'OK']], do_sleep=False)
self.print_ids(host, svc, router)
self.assertEqual(0, host.current_event_id)
self.assertEqual(0, host.last_event_id)
self.assertEqual(0, host.current_problem_id)
self.assertEqual(0, host.last_problem_id)
self.assertEqual(0, svc.current_event_id)
self.assertEqual(0, svc.last_event_id)
self.assertEqual(0, svc.current_problem_id)
self.assertEqual(0, svc.last_problem_id)
#--------------------------------------------------------------
# service reaches soft;1
# svc: 1,0,1,0
#--------------------------------------------------------------
print("- 1 x BAD get soft -------------------------------------")
self.scheduler_loop(1, [[svc, 2, 'BAD']], do_sleep=False)
self.print_ids(host, svc, router)
self.assertEqual(0, host.current_event_id)
self.assertEqual(0, host.last_event_id)
self.assertEqual(0, host.current_problem_id)
self.assertEqual(0, host.last_problem_id)
self.assertEqual(1, svc.current_event_id)
self.assertEqual(0, svc.last_event_id)
self.assertEqual(1, svc.current_problem_id)
self.assertEqual(0, svc.last_problem_id)
#--------------------------------------------------------------
# service reaches hard;2
# svc: 1,0,1,0
#--------------------------------------------------------------
print("- 1 x BAD get hard -------------------------------------")
self.scheduler_loop(1, [[svc, 2, 'BAD']], do_sleep=False)
self.print_ids(host, svc, router)
self.assertEqual(0, host.current_event_id)
self.assertEqual(0, host.last_event_id)
self.assertEqual(0, host.current_problem_id)
self.assertEqual(0, host.last_problem_id)
self.assertEqual(1, svc.current_event_id)
self.assertEqual(0, svc.last_event_id)
self.assertEqual(1, svc.current_problem_id)
self.assertEqual(0, svc.last_problem_id)
print("- 5 x BAD repeat -------------------------------------")
self.scheduler_loop(5, [[svc, 2, 'BAD']], do_sleep=False)
self.print_ids(host, svc, router)
self.assertEqual(0, host.current_event_id)
self.assertEqual(0, host.last_event_id)
self.assertEqual(0, host.current_problem_id)
self.assertEqual(0, host.last_problem_id)
self.assertEqual(1, svc.current_event_id)
self.assertEqual(0, svc.last_event_id)
self.assertEqual(1, svc.current_problem_id)
self.assertEqual(0, svc.last_problem_id)
#--------------------------------------------------------------
# now recover.
#--------------------------------------------------------------
self.scheduler_loop(1, [[svc, 0, 'GOOD']], do_sleep=False)
self.print_ids(host, svc, router)
self.assertEqual(0, host.current_event_id)
self.assertEqual(0, host.last_event_id)
self.assertEqual(0, host.current_problem_id)
self.assertEqual(0, host.last_problem_id)
self.assertEqual(2, svc.current_event_id)
self.assertEqual(1, svc.last_event_id)
self.assertEqual(0, svc.current_problem_id)
self.assertEqual(1, svc.last_problem_id)
#--------------------------------------------------------------
# service fails again, ok->w->c
#--------------------------------------------------------------
print("- 4 x BAD get hard with non-ok statechange -------------")
self.scheduler_loop(2, [[svc, 1, 'BAD']], do_sleep=False)
self.print_ids(host, svc, router)
self.assertEqual(0, host.current_event_id)
self.assertEqual(0, host.last_event_id)
self.assertEqual(0, host.current_problem_id)
self.assertEqual(0, host.last_problem_id)
self.assertEqual(3, svc.current_event_id)
self.assertEqual(2, svc.last_event_id)
self.assertEqual(2, svc.current_problem_id)
self.assertEqual(0, svc.last_problem_id)
# another statechange
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=False)
self.print_ids(host, svc, router)
self.assertEqual(0, host.current_event_id)
self.assertEqual(0, host.last_event_id)
self.assertEqual(0, host.current_problem_id)
self.assertEqual(0, host.last_problem_id)
self.assertEqual(4, svc.current_event_id)
self.assertEqual(3, svc.last_event_id)
self.assertEqual(2, svc.current_problem_id)
self.assertEqual(0, svc.last_problem_id)
#--------------------------------------------------------------
# now recover.
#--------------------------------------------------------------
self.scheduler_loop(1, [[svc, 0, 'GOOD']], do_sleep=False)
self.print_ids(host, svc, router)
self.assertEqual(0, host.current_event_id)
self.assertEqual(0, host.last_event_id)
self.assertEqual(0, host.current_problem_id)
self.assertEqual(0, host.last_problem_id)
self.assertEqual(5, svc.current_event_id)
self.assertEqual(4, svc.last_event_id)
self.assertEqual(0, svc.current_problem_id)
self.assertEqual(2, svc.last_problem_id)
#--------------------------------------------------------------
# mix in two hosts
#--------------------------------------------------------------
print("- 4 x BAD get hard with non-ok statechange -------------")
self.scheduler_loop(2, [[router, 2, 'DOWN']], do_sleep=False)
self.print_ids(host, svc, router)
self.assertEqual(6, SchedulingItem.current_event_id)
self.assertEqual(3, SchedulingItem.current_problem_id)
self.assertEqual(0, host.current_event_id)
self.assertEqual(0, host.last_event_id)
self.assertEqual(0, host.current_problem_id)
self.assertEqual(0, host.last_problem_id)
self.assertEqual(5, svc.current_event_id)
self.assertEqual(4, svc.last_event_id)
self.assertEqual(0, svc.current_problem_id)
self.assertEqual(2, svc.last_problem_id)
self.assertEqual(6, router.current_event_id)
self.assertEqual(0, router.last_event_id)
self.assertEqual(3, router.current_problem_id)
self.assertEqual(0, router.last_problem_id)
# add chaos
self.scheduler_loop(1, [[svc, 2, 'BAD']], do_sleep=False)
self.scheduler_loop(2, [[router, 0, 'UP']], do_sleep=False)
self.scheduler_loop(5, [[host, 2, 'DOWN']], do_sleep=False)
self.print_ids(host, svc, router)
self.assertEqual(9, SchedulingItem.current_event_id)
self.assertEqual(5, SchedulingItem.current_problem_id)
self.assertEqual(9, host.current_event_id)
self.assertEqual(0, host.last_event_id)
self.assertEqual(5, host.current_problem_id)
self.assertEqual(0, host.last_problem_id)
self.assertEqual(7, svc.current_event_id)
self.assertEqual(5, svc.last_event_id)
self.assertEqual(4, svc.current_problem_id)
self.assertEqual(0, svc.last_problem_id)
self.assertEqual(8, router.current_event_id)
self.assertEqual(6, router.last_event_id)
self.assertEqual(0, router.current_problem_id)
self.assertEqual(3, router.last_problem_id)
if __name__ == '__main__':
unittest.main()
| 10,639
|
Python
|
.py
| 202
| 44.772277
| 156
| 0.58749
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,345
|
test_linkify_template.py
|
shinken-solutions_shinken/test/test_linkify_template.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestLinkifyTemplate(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_linkify_template.cfg')
def test_linkify_template(self):
svc = self.conf.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
b = svc.is_correct()
self.assertFalse(b)
if __name__ == '__main__':
unittest.main()
| 1,357
|
Python
|
.py
| 33
| 38.515152
| 90
| 0.742966
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,346
|
test_sslv3_disabled.py
|
shinken-solutions_shinken/test/test_sslv3_disabled.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This test checks that sslv3 is disabled when SSL is used with a cherrypy backend to secure against the Poodle vulnerability (https://poodlebleed.com)
from __future__ import absolute_import, division, print_function, unicode_literals
import subprocess
from time import sleep
import requests
import ssl
try:
import OpenSSL
except ImportError:
OpenSSL = None
from shinken_test import *
import shinken.log as shinken_log
from shinken.daemons.schedulerdaemon import Shinken
from shinken.daemons.arbiterdaemon import Arbiter
daemons_config = {
Shinken: "etc/test_sslv3_disabled/schedulerd.ini",
Arbiter: ["etc/test_sslv3_disabled/shinken.cfg"]
}
class testSchedulerInit(ShinkenTest):
def setUp(self):
time_hacker.set_real_time()
def create_daemon(self):
cls = Shinken
return cls(daemons_config[cls], False, True, False, None, '')
@unittest.skipIf(OpenSSL is None, "Test requires OpenSSL")
def test_scheduler_init(self):
if not hasattr(ssl, 'SSLContext'):
print('BAD ssl version for testing, bailing out')
return
if not hasattr(ssl, 'PROTOCOL_SSLv3'):
print('BAD ssl version for testing, no PROTOCOL_SSLv3 support')
return
shinken_log.local_log = None # otherwise get some "trashs" logs..
d = self.create_daemon()
d.load_config_file()
d.http_backend = 'cherrypy'
d.do_daemon_init_and_start(fake=True)
d.load_modules_manager()
# Launch an arbiter so that the scheduler get a conf and init
subprocess.Popen(["../bin/shinken-arbiter.py", "-c", daemons_config[Arbiter][0], "-d"])
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
ctx.check_hostname=False
ctx.verify_mode=ssl.CERT_NONE
def connect():
with socket.create_connection(("localhost", 9998)) as sock:
with ctx.wrap_socket(sock, server_hostname="localhost") as ssock:
pass
self.assertRaises(ssl.SSLError, connect)
try:
connect()
except ssl.SSLError as e:
self.assertEqual(e.reason, 'SSLV3_ALERT_HANDSHAKE_FAILURE')
sleep(2)
pid = int(file("tmp/arbiterd.pid").read())
print ("KILLING %d" % pid)*50
os.kill(int(file("tmp/arbiterd.pid").read()), 2)
d.do_stop()
if __name__ == '__main__':
unittest.main()
| 3,238
|
Python
|
.py
| 79
| 35.21519
| 151
| 0.686424
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,347
|
test_non_stripped_list.py
|
shinken-solutions_shinken/test/test_non_stripped_list.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestNonStrippedList(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_non_stripped_list.cfg')
def test_dummy(self):
now = time.time()
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
host = self.sched.hosts.find_by_name("OBIWAN")
self.assertIn('d', host.flap_detection_options)
if __name__ == '__main__':
unittest.main()
| 1,499
|
Python
|
.py
| 38
| 36
| 82
| 0.724518
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,348
|
test_nohostsched.py
|
shinken-solutions_shinken/test/test_nohostsched.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestHostspecialSched(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_nohostsched.cfg')
# The hosts can have no check_period nor check_interval.
# It's valid, and say: 24x7 and 5min interval in fact.
def test_nohostsched(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("moncul")
self.assertIsNot(host, None)
print("check", host.next_chk)
print("Check in", host.next_chk - now)
self.assertLess(host.next_chk - now, 301)
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
print("Loop")
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2']])
self.assertEqual('UP', host.state)
self.assertEqual('HARD', host.state_type)
# Reschedule the host as a normal way
host.schedule()
print("Final", host.next_chk, host.is_in_checking())
print("Next check?", host.next_chk - now)
print("Next check should be still < 300", host.next_chk - now)
self.assertLess(host.next_chk - now, 301)
# but in 5min in fact, so more than 290,
# something like 299.0
self.assertGreater(host.next_chk - now, 290)
if __name__ == '__main__':
unittest.main()
| 2,447
|
Python
|
.py
| 58
| 36.948276
| 82
| 0.680118
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,349
|
test_maintenance_check.py
|
shinken-solutions_shinken/test/test_maintenance_check.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test object properties overriding.
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import unittest, ShinkenTest, time
from shinken.objects.timeperiod import Timeperiod
import re
class TestMaintenaceCheck(ShinkenTest):
def setUp(self):
self.setup_with_file("etc/shinken_maintenance_check.cfg")
def check_object_status(self, obj, wanted_downtime, wanted_notifications):
self.assertIs(obj.in_scheduled_downtime, wanted_downtime)
if wanted_downtime is True:
self.assertTrue(obj.in_scheduled_downtime)
self.assertTrue(obj.scheduled_downtime_depth > 0)
self.assertIsNotNone(obj.in_maintenance)
else:
self.assertFalse(obj.in_scheduled_downtime)
self.assertTrue(obj.scheduled_downtime_depth == 0)
self.assertIsNone(obj.in_maintenance)
if wanted_notifications is True:
self.assertFalse(obj.notification_is_blocked_by_item("PROBLEM"))
else:
self.assertTrue(obj.notification_is_blocked_by_item("PROBLEM"))
def test_maintenance_check(self):
period = self.sched.timeperiods.find_by_name("24x7")
hst1 = self.sched.hosts.find_by_name("test_host_1")
hst2 = self.sched.hosts.find_by_name("test_host_2")
svc11 = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "test_service_1")
svc12 = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "test_service_2")
svc21 = self.sched.services.find_srv_by_name_and_hostname("test_host_2", "test_service_1")
svc22 = self.sched.services.find_srv_by_name_and_hostname("test_host_2", "test_service_2")
# Tests objets are correctly configurred
self.assertIsNotNone(hst1)
self.assertIsNone(hst1.maintenance_check_period)
self.assertIsNotNone(hst2)
self.assertIs(hst2.maintenance_check_period, period)
self.assertIsNotNone(svc11)
self.assertIsNone(svc11.maintenance_check_period)
self.assertIsNotNone(svc12)
self.assertIs(svc12.maintenance_check_period, period)
self.assertIsNotNone(svc21)
self.assertIsNone(svc21.maintenance_check_period)
self.assertIsNotNone(svc22)
self.assertIs(svc22.maintenance_check_period, period)
# Run standard checks
self.scheduler_loop(2, [
{
"item": hst1,
"exit_status": 0,
"output": "UP test_host_1"
},
{
"item": hst2,
"exit_status": 0,
"output": "UP test_host_2"
},
{
"item": svc11,
"exit_status": 0,
"output": "OK test_host_1/test_service_1"
},
{
"item": svc12,
"exit_status": 0,
"output": "OK test_host_1/test_service_2"
},
{
"item": svc21,
"exit_status": 0,
"output": "OK test_host_2/test_service_1"
},
{
"item": svc22,
"exit_status": 0,
"output": "OK test_host_2/test_service_2"
},
])
# Tests objets state
self.check_object_status(hst1, False, True)
self.check_object_status(hst2, False, True)
self.check_object_status(svc11, False, True)
self.check_object_status(svc12, False, True)
self.check_object_status(svc21, False, True)
self.check_object_status(svc22, False, True)
# Run maintenance check (disabled)
self.scheduler_loop(1, [
{
"item": hst2,
"exit_status": 2,
"output": "MAINTENANCE test_host_2",
"check_variant": "maintenance"
},
{
"item": svc12,
"exit_status": 2,
"output": "MAINTENANCE test_host_1/test_service_2",
"check_variant": "maintenance"
},
{
"item": svc22,
"exit_status": 2,
"output": "MAINTENANCE test_host_2/test_service_2",
"check_variant": "maintenance"
},
])
# Tests objets state
self.check_object_status(hst1, False, True)
self.check_object_status(hst2, True, False)
self.check_object_status(svc11, False, True)
self.check_object_status(svc12, True, False)
# hst2 is under downtime, so svc21 has notifications disabled
self.check_object_status(svc21, False, False)
self.check_object_status(svc22, True, False)
# Run maintenance check (back to production)
self.scheduler_loop(1, [
{
"item": hst2,
"exit_status": 0,
"output": "PRODUCTION test_host_2",
"check_variant": "maintenance"
},
{
"item": svc12,
"exit_status": 0,
"output": "PRODUCTION test_host_1/test_service_2",
"check_variant": "maintenance"
},
{
"item": svc22,
"exit_status": 0,
"output": "PRODUCTION test_host_2/test_service_2",
"check_variant": "maintenance"
},
])
self.check_object_status(hst1, False, True)
self.check_object_status(hst2, False, True)
self.check_object_status(svc11, False, True)
self.check_object_status(svc12, False, True)
self.check_object_status(svc21, False, True)
self.check_object_status(svc22, False, True)
def test_maintenance_check_timeout(self):
hst1 = self.sched.hosts.find_by_name("test_host_1")
hst2 = self.sched.hosts.find_by_name("test_host_2")
svc12 = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "test_service_2")
svc22 = self.sched.services.find_srv_by_name_and_hostname("test_host_2", "test_service_2")
self.scheduler_loop(2, [
{
"item": hst1,
"exit_status": 0,
"output": "OK test_host_1"
},
{
"item": hst2,
"exit_status": 0,
"output": "OK test_host_1"
},
{
"item": svc12,
"exit_status": 0,
"output": "OK test_host_1/test_service_2"
},
{
"item": svc22,
"exit_status": 0,
"output": "OK test_host_2/test_service_2"
},
])
# Run maintenance check (two are timed out)
self.scheduler_loop(1, [
{
"item": svc12,
"exit_status": 2,
"output": "MAINTENANCE test_host_1/test_service_2",
"check_variant": "maintenance",
"timeout": True,
},
{
"item": svc22,
"exit_status": 2,
"output": "MAINTENANCE test_host_2/test_service_2",
"check_variant": "maintenance",
},
])
# Tests objets state
self.check_object_status(svc12, False, True)
self.check_object_status(svc22, True, False)
def test_maintenance_period_check_overlap(self):
hst2 = self.sched.hosts.find_by_name("test_host_2")
svc22 = self.sched.services.find_srv_by_name_and_hostname("test_host_2", "test_service_2")
# be sure we have some time before a new minute begins.
# otherwise we get a race condition and a failed test here.
now = time.time()
x = time.gmtime(now)
while x.tm_sec < 50:
time.sleep(1)
now = time.time()
x = time.gmtime(now)
now = time.time()
start_tuple = time.localtime(now + 60)
nowday = time.strftime("%A", start_tuple).lower()
soonstart = time.strftime("%H:%M", start_tuple)
end_tuple = time.localtime(now + 180)
soonend = time.strftime("%H:%M", end_tuple)
dt_range = "%s %s-%s" % (nowday, soonstart, soonend)
t = Timeperiod()
t.timeperiod_name = ""
t.resolve_daterange(t.dateranges, dt_range)
t_start = t.get_next_valid_time_from_t(now)
t_end = t.get_next_invalid_time_from_t(t_start + 1) - 1
hst2.maintenance_period = t
svc22.maintenance_period = t
self.assertIsNone(hst2.in_maintenance)
self.assertIsNone(svc22.in_maintenance)
# Run maintenance check (out of production)
self.scheduler_loop(1, [
{
"item": hst2,
"exit_status": 0,
"output": "UP test_host_2"
},
{
"item": svc22,
"exit_status": 0,
"output": "OK test_host_2/test_service_2"
},
{
"item": hst2,
"exit_status": 2,
"output": "MAINTENANCE test_host_2",
"check_variant": "maintenance"
},
{
"item": svc22,
"exit_status": 2,
"output": "MAINTENANCE test_host_2/test_service_2",
"check_variant": "maintenance"
},
])
# Downtimes are created because of maintenance check result
self.check_object_status(hst2, True, False)
self.check_object_status(svc22, True, False)
self.assertEqual(len(self.sched.downtimes), 2)
self.assertIn(hst2.downtimes[0], self.sched.downtimes.values())
self.assertIn(svc22.downtimes[0], self.sched.downtimes.values())
hst2_dt_id = hst2.downtimes[0].id
self.assertEqual(hst2_dt_id, hst2.in_maintenance)
svc22_dt_id = svc22.downtimes[0].id
self.assertEqual(svc22_dt_id, svc22.in_maintenance)
self.assertLess(hst2.downtimes[0].end_time, t_end)
self.assertLess(svc22.downtimes[0].end_time, t_end)
# now let the scheduler run and wait until the maintenance period begins
# it is now 10 seconds before the full minute. run for 30 seconds
# in 1-second-intervals. this should be enough to trigger the downtime
# in 10 seconds from now the downtime starts
self.scheduler_loop(30, [
{
"item": hst2,
"exit_status": 0,
"output": "UP test_host_2"
},
{
"item": svc22,
"exit_status": 0,
"output": "OK test_host_2/test_service_2"
},
{
"item": hst2,
"exit_status": 2,
"output": "MAINTENANCE test_host_2",
"check_variant": "maintenance"
},
{
"item": svc22,
"exit_status": 2,
"output": "MAINTENANCE test_host_2/test_service_2",
"check_variant": "maintenance"
},
], do_sleep=True, sleep_time=1)
# Downtimes are set from maintenance period, which has precedence
self.check_object_status(hst2, True, False)
self.check_object_status(svc22,True, False)
self.assertEqual(len(self.sched.downtimes), 2)
self.assertIn(hst2.downtimes[0], self.sched.downtimes.values())
self.assertIn(svc22.downtimes[0], self.sched.downtimes.values())
self.assertEqual(hst2_dt_id, hst2.in_maintenance)
self.assertEqual(svc22_dt_id, svc22.in_maintenance)
self.assertEqual(hst2.downtimes[0].end_time, t_end)
self.assertEqual(svc22.downtimes[0].end_time, t_end)
#time.sleep(180)
self.scheduler_loop(180, [
{
"item": hst2,
"exit_status": 0,
"output": "UP test_host_2"
},
{
"item": svc22,
"exit_status": 0,
"output": "OK test_host_2/test_service_2"
},
{
"item": hst2,
"exit_status": 2,
"output": "MAINTENANCE test_host_2",
"check_variant": "maintenance"
},
{
"item": svc22,
"exit_status": 2,
"output": "MAINTENANCE test_host_2/test_service_2",
"check_variant": "maintenance"
},
], do_sleep=True, sleep_time=1)
# Maintenace period has expired, downtimes are extended because of
# maintenance check result
self.check_object_status(hst2, True, False)
self.check_object_status(svc22, True, False)
self.assertEqual(len(self.sched.downtimes), 2)
self.assertIn(hst2.downtimes[0], self.sched.downtimes.values())
self.assertIn(svc22.downtimes[0], self.sched.downtimes.values())
self.assertEqual(hst2_dt_id, hst2.in_maintenance)
self.assertEqual(svc22_dt_id, svc22.in_maintenance)
self.assertGreater(hst2.downtimes[0].end_time, t_end)
self.assertGreater(svc22.downtimes[0].end_time, t_end)
def test_maintenance_check_errors(self):
hst1 = self.sched.hosts.find_by_name("test_host_1")
hst2 = self.sched.hosts.find_by_name("test_host_2")
svc12 = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "test_service_2")
svc22 = self.sched.services.find_srv_by_name_and_hostname("test_host_2", "test_service_2")
self.scheduler_loop(2, [
{
"item": hst1,
"exit_status": 0,
"output": "UP test_host_1"
},
{
"item": hst2,
"exit_status": 0,
"output": "UP test_host_2"
},
{
"item": svc12,
"exit_status": 0,
"output": "OK test_host_1/test_service_2"
},
{
"item": svc22,
"exit_status": 0,
"output": "OK test_host_2/test_service_2"
},
])
self.scheduler_loop(1, [
{
"item": hst2,
"exit_status": 2,
"output": "MAINTENANCE test_host_2",
"check_variant": "maintenance"
},
{
"item": svc12,
"exit_status": 2,
"output": "MAINTENANCE test_host_2/test_service_2",
"check_variant": "maintenance"
},
{
"item": svc22,
"exit_status": 2,
"output": "MAINTENANCE test_host_2/test_service_2",
"check_variant": "maintenance"
},
], do_sleep=True, sleep_time=1)
self.scheduler_loop(1, [
{
"item": hst2,
"exit_status": 1,
"output": "invalid command test_host_2",
"check_variant": "maintenance"
},
{
"item": svc12,
"exit_status": 3,
"output": "unknown option test_host_2/test_service_2",
"check_variant": "maintenance"
},
{
"item": svc22,
"exit_status": 5,
"output": "bad hostname test_host_2/test_service_2",
"check_variant": "maintenance"
},
], do_sleep=True, sleep_time=1)
# Get the arbiter's log broks
#[b.prepare() for b in self.broks]
logs = [b.data['log'] for b in self.broks if b.type == 'log']
self.assertEqual(3, len([log for log in logs if re.search('got an invalid return code', log)]))
# Invalid returcode should get the item back to production state
self.check_object_status(hst2, False, True)
self.check_object_status(svc12, False, True)
self.check_object_status(svc22, False, True)
if __name__ == "__main__":
unittest.main()
| 17,060
|
Python
|
.py
| 421
| 28.47981
| 103
| 0.541089
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,350
|
test_no_host_template.py
|
shinken-solutions_shinken/test/test_no_host_template.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestNoHostTemplate(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_no_host_template.cfg')
def test_host_without_a_template(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("my_host")
b = host.is_correct()
self.assertTrue(b)
if __name__ == '__main__':
unittest.main()
| 1,517
|
Python
|
.py
| 39
| 35.307692
| 82
| 0.719537
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,351
|
test_external_commands.py
|
shinken-solutions_shinken/test/test_external_commands.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
from shinken.external_command import ExternalCommandManager
import os
class TestConfig(ShinkenTest):
# setUp is inherited from ShinkenTest
def setUp(self):
self.setup_with_file('etc/shinken_external_commands.cfg')
time_hacker.set_real_time()
def send_cmd(self, line):
s = '[%d] %s\n' % (int(time.time()), line)
print("Writing %s in %s" % (s, self.conf.command_file))
fd = open(self.conf.command_file, 'wb')
fd.write(s)
fd.close()
def test_external_commands(self):
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
router = self.sched.hosts.find_by_name("test_router_0")
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [svc, 2, 'BAD | value1=0 value2=0']])
self.assertEqual('UP', host.state)
self.assertEqual('HARD', host.state_type)
excmd = '[%d] PROCESS_HOST_CHECK_RESULT;test_host_0;2;Bob is not happy' % time.time()
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
self.assertEqual('DOWN', host.state)
self.assertEqual('Bob is not happy', host.output)
# Now with performance data
excmd = '[%d] PROCESS_HOST_CHECK_RESULT;test_host_0;2;Bob is not happy|rtt=9999' % time.time()
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
self.assertEqual('DOWN', host.state)
self.assertEqual('Bob is not happy', host.output)
self.assertEqual('rtt=9999', host.perf_data)
# Now with full-blown performance data. Here we have to watch out:
# Is a ";" a separator for the external command or is it
# part of the performance data?
excmd = '[%d] PROCESS_HOST_CHECK_RESULT;test_host_0;2;Bob is not happy|rtt=9999;5;10;0;10000' % time.time()
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
self.assertEqual('DOWN', host.state)
self.assertEqual('Bob is not happy', host.output)
print("perf (%s)" % host.perf_data)
self.assertEqual('rtt=9999;5;10;0;10000', host.perf_data)
# The same with a service
excmd = '[%d] PROCESS_SERVICE_CHECK_RESULT;test_host_0;test_ok_0;1;Bobby is not happy|rtt=9999;5;10;0;10000' % time.time()
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
self.assertEqual('WARNING', svc.state)
self.assertEqual('Bobby is not happy', svc.output)
print("perf (%s)" % svc.perf_data)
self.assertEqual('rtt=9999;5;10;0;10000', svc.perf_data)
# ACK SERVICE
excmd = '[%d] ACKNOWLEDGE_SVC_PROBLEM;test_host_0;test_ok_0;2;1;1;Big brother;Acknowledge service' % int(time.time())
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
self.assertEqual('WARNING', svc.state)
self.assertEqual(True, svc.problem_has_been_acknowledged)
excmd = '[%d] REMOVE_SVC_ACKNOWLEDGEMENT;test_host_0;test_ok_0' % int(time.time())
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
self.assertEqual('WARNING', svc.state)
self.assertEqual(False, svc.problem_has_been_acknowledged)
# Service is going ok ...
excmd = '[%d] PROCESS_SERVICE_CHECK_RESULT;test_host_0;test_ok_0;0;Bobby is happy now!|rtt=9999;5;10;0;10000' % time.time()
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
self.assertEqual('OK', svc.state)
self.assertEqual('Bobby is happy now!', svc.output)
self.assertEqual('rtt=9999;5;10;0;10000', svc.perf_data)
# Host is going up ...
excmd = '[%d] PROCESS_HOST_CHECK_RESULT;test_host_0;0;Bob is also happy now!' % time.time()
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
self.assertEqual('UP', host.state)
self.assertEqual('Bob is also happy now!', host.output)
# Clean the command_file
#try:
# os.unlink(self.conf.command_file)
#except:
# pass
# Now with PAST DATA. We take the router because it was not called from now.
past = int(time.time() - 30)
excmd = '[%d] PROCESS_HOST_CHECK_RESULT;test_router_0;2;Bob is not happy|rtt=9999;5;10;0;10000' % past
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
self.assertEqual('DOWN', router.state)
self.assertEqual('Bob is not happy', router.output)
print("perf (%s)" % router.perf_data)
self.assertEqual('rtt=9999;5;10;0;10000', router.perf_data)
print("Is the last check agree?", past, router.last_chk)
self.assertEqual(router.last_chk, past)
# Now an even earlier check, should NOT be take
very_past = int(time.time() - 3600)
excmd = '[%d] PROCESS_HOST_CHECK_RESULT;test_router_0;2;Bob is not happy|rtt=9999;5;10;0;10000' % very_past
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
self.assertEqual('DOWN', router.state)
self.assertEqual('Bob is not happy', router.output)
print("perf (%s)" % router.perf_data)
self.assertEqual('rtt=9999;5;10;0;10000', router.perf_data)
print("Is the last check agree?", very_past, router.last_chk)
self.assertEqual(router.last_chk, past)
# Now with crappy characters, like é
host = self.sched.hosts.find_by_name("test_router_0")
excmd = '[%d] PROCESS_HOST_CHECK_RESULT;test_router_0;2;Bob got a crappy character é and so is not not happy|rtt=9999' % int(time.time())
self.sched.run_external_command(excmd)
self.scheduler_loop(2, [])
self.assertEqual('DOWN', host.state)
self.assertEqual(u'Bob got a crappy character é and so is not not happy', host.output)
self.assertEqual('rtt=9999', host.perf_data)
# ACK HOST
excmd = '[%d] ACKNOWLEDGE_HOST_PROBLEM;test_router_0;2;1;1;Big brother;test' % int(time.time())
self.sched.run_external_command(excmd)
self.scheduler_loop(2, [])
print("Host state", host.state, host.problem_has_been_acknowledged)
self.assertEqual('DOWN', host.state)
self.assertEqual(True, host.problem_has_been_acknowledged)
# REMOVE ACK HOST
excmd = '[%d] REMOVE_HOST_ACKNOWLEDGEMENT;test_router_0' % int(time.time())
self.sched.run_external_command(excmd)
self.scheduler_loop(2, [])
print("Host state", host.state, host.problem_has_been_acknowledged)
self.assertEqual('DOWN', host.state)
self.assertEqual(False, host.problem_has_been_acknowledged)
# RESTART_PROGRAM
excmd = '[%d] RESTART_PROGRAM' % int(time.time())
self.sched.run_external_command(excmd)
self.scheduler_loop(2, [])
self.assert_any_log_match('RESTART')
self.assert_any_log_match('I awoke after sleeping 3 seconds')
# RELOAD_CONFIG
excmd = '[%d] RELOAD_CONFIG' % int(time.time())
self.sched.run_external_command(excmd)
self.scheduler_loop(2, [])
self.assert_any_log_match('RELOAD')
self.assert_any_log_match('I awoke after sleeping 2 seconds')
# Show recent logs
self.show_logs()
# Tests sending passive check results for unconfigured hosts to a scheduler
def test_unknown_check_result_command_scheduler(self):
self.sched.conf.accept_passive_unknown_check_results = True
# Sched receives known host but unknown service service_check_result
del self.sched.broks[:]
excmd = '[%d] PROCESS_SERVICE_CHECK_RESULT;test_host_0;unknownservice;1;Bobby is not happy|rtt=9999;5;10;0;10000' % time.time()
self.sched.run_external_command(excmd)
broks = [b for b in self.sched.broks if b.type == 'unknown_service_check_result']
self.assertTrue(len(broks) == 1)
# Sched receives unknown host and service service_check_result
del self.sched.broks[:]
excmd = '[%d] PROCESS_SERVICE_CHECK_RESULT;unknownhost;unknownservice;1;Bobby is not happy|rtt=9999;5;10;0;10000' % time.time()
self.sched.run_external_command(excmd)
broks = [b for b in self.sched.broks if b.type == 'unknown_service_check_result']
self.assertTrue(len(broks) == 1)
# Sched receives unknown host host_check_result
del self.sched.broks[:]
excmd = '[%d] PROCESS_HOST_CHECK_RESULT;unknownhost;1;Bobby is not happy|rtt=9999;5;10;0;10000' % time.time()
self.sched.run_external_command(excmd)
broks = [b for b in self.sched.broks if b.type == 'unknown_host_check_result']
self.assertTrue(len(broks) == 1)
# Now turn it off...
self.sched.conf.accept_passive_unknown_check_results = False
# Sched receives known host but unknown service service_check_result
del self.sched.broks[:]
excmd = '[%d] PROCESS_SERVICE_CHECK_RESULT;test_host_0;unknownservice;1;Bobby is not happy|rtt=9999;5;10;0;10000' % time.time()
self.sched.run_external_command(excmd)
broks = [b for b in self.sched.broks if b.type == 'unknown_service_check_result']
self.assertTrue(len(broks) == 0)
self.assert_log_match(1, 'A command was received for service .* on host .*, but the service could not be found!')
self.clear_logs()
#Tests sending passive check results for unconfigured hosts to a receiver
def test_unknown_check_result_command_receiver(self):
receiverdaemon = Receiver(None, False, False, False, None)
receiverdaemon.direct_routing = True
receiverdaemon.accept_passive_unknown_check_results = True
# Receiver receives unknown host external command
excmd = ExternalCommand('[%d] PROCESS_SERVICE_CHECK_RESULT;test_host_0;unknownservice;1;Bobby is not happy|rtt=9999;5;10;0;10000' % time.time())
receiverdaemon.unprocessed_external_commands.append(excmd)
receiverdaemon.push_external_commands_to_schedulers()
broks = [b for b in receiverdaemon.broks if b.type == 'unknown_service_check_result']
self.assertEqual(len(broks), 1)
# now turn it off...
receiverdaemon.accept_passive_unknown_check_results = False
excmd = ExternalCommand('[%d] PROCESS_SERVICE_CHECK_RESULT;test_host_0;unknownservice;1;Bobby is not happy|rtt=9999;5;10;0;10000' % time.time())
receiverdaemon.unprocessed_external_commands.append(excmd)
receiverdaemon.push_external_commands_to_schedulers()
del receiverdaemon.broks[:]
broks = [b for b in receiverdaemon.broks if b.type == 'unknown_service_check_result']
self.assertEqual(len(broks), 0)
def test_unknown_check_result_brok(self):
# unknown_host_check_result_brok
excmd = '[1234567890] PROCESS_HOST_CHECK_RESULT;test_host_0;2;Bob is not happy'
expected = {'time_stamp': 1234567890, 'return_code': '2', 'host_name': 'test_host_0', 'output': 'Bob is not happy', 'perf_data': None}
result = ExternalCommandManager.get_unknown_check_result_brok(excmd).data
self.assertEqual(expected, result)
# unknown_host_check_result_brok with perfdata
excmd = '[1234567890] PROCESS_HOST_CHECK_RESULT;test_host_0;2;Bob is not happy|rtt=9999'
expected = {'time_stamp': 1234567890, 'return_code': '2', 'host_name': 'test_host_0', 'output': 'Bob is not happy', 'perf_data': 'rtt=9999'}
result = ExternalCommandManager.get_unknown_check_result_brok(excmd).data
self.assertEqual(expected, result)
# unknown_service_check_result_brok
excmd = '[1234567890] PROCESS_HOST_CHECK_RESULT;host-checked;0;Everything OK'
expected = {'time_stamp': 1234567890, 'return_code': '0', 'host_name': 'host-checked', 'output': 'Everything OK', 'perf_data': None}
result = ExternalCommandManager.get_unknown_check_result_brok(excmd).data
self.assertEqual(expected, result)
# unknown_service_check_result_brok with perfdata
excmd = '[1234567890] PROCESS_SERVICE_CHECK_RESULT;test_host_0;test_ok_0;1;Bobby is not happy|rtt=9999;5;10;0;10000'
expected = {'host_name': 'test_host_0', 'time_stamp': 1234567890, 'service_description': 'test_ok_0', 'return_code': '1', 'output': 'Bobby is not happy', 'perf_data': 'rtt=9999;5;10;0;10000'}
result = ExternalCommandManager.get_unknown_check_result_brok(excmd).data
self.assertEqual(expected, result)
def test_change_and_reset_modattr(self):
# Receiver receives unknown host external command
excmd = '[%d] CHANGE_SVC_MODATTR;test_host_0;test_ok_0;1' % time.time()
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, []) # Need 2 run for get then consume)
svc = self.conf.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
self.assertEqual(1, svc.modified_attributes)
self.assertFalse(getattr(svc, DICT_MODATTR["MODATTR_NOTIFICATIONS_ENABLED"].attribute))
def test_change_retry_host_check_interval(self):
excmd = '[%d] CHANGE_RETRY_HOST_CHECK_INTERVAL;test_host_0;42' % time.time()
self.sched.run_external_command(excmd)
self.scheduler_loop(1, [])
self.scheduler_loop(1, [])
hst = self.conf.hosts.find_by_name("test_host_0")
self.assertEqual(2048, hst.modified_attributes)
self.assertEqual(getattr(hst, DICT_MODATTR["MODATTR_RETRY_CHECK_INTERVAL"].attribute), 42)
self.assert_no_log_match("A command was received for service.*")
if __name__ == '__main__':
unittest.main()
| 15,528
|
Python
|
.py
| 264
| 50.693182
| 199
| 0.664476
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,352
|
test_poller_tag_get_checks.py
|
shinken-solutions_shinken/test/test_poller_tag_get_checks.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestPollerTagGetchecks(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_poller_tag_get_checks.cfg')
def test_good_checks_get_only_tags_with_specific_tags(self):
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
# schedule the host so it will have a check :)
# and for ce the execution now
host.schedule()
self.assertEqual('mytestistrue', host.check_command.command.poller_tag)
for a in host.actions:
print("Tag", a.poller_tag)
a.t_to_go = 0
svc.schedule()
for a in svc.actions:
print("Tag", a.poller_tag)
a.t_to_go = 0
# the scheduler need to get this new checks in its own queues
self.sched.get_new_actions()
# Ask for untag checks only
untaggued_checks = self.sched.get_to_run_checks(True, False, poller_tags=['None'])
print("Got untaggued_checks", untaggued_checks)
self.assertGreater(len(untaggued_checks), 0)
for c in untaggued_checks:
# Should be the service one, but not the host one
self.assertTrue(c.command.startswith('plugins/test_servicecheck.pl'))
# Now get only tag ones
taggued_checks = self.sched.get_to_run_checks(True, False, poller_tags=['mytestistrue'])
self.assertGreater(len(taggued_checks), 0)
for c in taggued_checks:
# Should be the host one only
self.assertTrue(c.command.startswith('plugins/test_hostcheck.pl'))
def test_good_checks_get_only_tags_with_specific_module_types(self):
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
# schedule the host so it will have a check :)
# and for ce the execution now
host.schedule()
self.assertEqual('mytestistrue', host.check_command.command.poller_tag)
for a in host.actions:
print("Tag", a.poller_tag)
a.t_to_go = 0
svc.schedule()
for a in svc.actions:
print("Tag", a.poller_tag)
a.t_to_go = 0
# the scheduler need to get this new checks in its own queues
self.sched.get_new_actions()
# Ask for badly named module type
untaggued_checks = self.sched.get_to_run_checks(True, False, poller_tags=['None'], module_types=['fork'])
print("Got untaggued_checks for forks", untaggued_checks)
self.assertGreater(len(untaggued_checks), 0)
print("NB CHECKS", len(untaggued_checks))
for c in untaggued_checks:
print(c.command)
# Should be the service one, but not the host one
self.assertTrue(c.command.startswith('plugins/test_servicecheck.pl') or c.command.startswith('plugins/test_hostcheck.pl'))
# Now get only tag ones and with a bad module type, so get NOTHING
taggued_checks = self.sched.get_to_run_checks(True, False, poller_tags=['mytestistrue'], module_types=['myassischicken'])
self.assertEqual(0, len(taggued_checks))
if __name__ == '__main__':
unittest.main()
| 4,651
|
Python
|
.py
| 94
| 42.085106
| 134
| 0.665713
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,353
|
test_template_loop.py
|
shinken-solutions_shinken/test/test_template_loop.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestTemplateLoop(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_template_loop.cfg')
def test_dummy(self):
self.assertFalse(self.conf.conf_is_correct)
if __name__ == '__main__':
unittest.main()
| 1,244
|
Python
|
.py
| 31
| 37.935484
| 82
| 0.754983
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,354
|
test_services.py
|
shinken-solutions_shinken/test/test_services.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
import copy
from shinken_test import *
class TestService(ShinkenTest):
# setUp is inherited from ShinkenTest
def get_svc(self):
return self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
# Look if get_*_name return the good result
def test_get_name(self):
svc = self.get_svc()
print(svc.get_dbg_name())
self.assertEqual('test_ok_0', svc.get_name())
self.assertEqual('test_host_0/test_ok_0', svc.get_dbg_name())
# getstate should be with all properties in dict class + id
# check also the setstate
def test___getstate__(self):
svc = self.get_svc()
cls = svc.__class__
# We get the state
state = svc.__getstate__()
# Check it's the good length
self.assertEqual(len(cls.properties) + len(cls.running_properties) + 1, len(state))
# we copy the service
svc_copy = copy.copy(svc)
# reset the state in the original service
svc.__setstate__(state)
# And it should be the same:then before :)
for p in cls.properties:
## print(getattr(svc_copy, p))
## print(getattr(svc, p))
self.assertEqual(getattr(svc, p), getattr(svc_copy, p) )
# Look if it can detect all incorrect cases
def test_is_correct(self):
svc = self.get_svc()
# first it's ok
self.assertEqual(True, svc.is_correct())
# Now try to delete a required property
max_check_attempts = svc.max_check_attempts
del svc.max_check_attempts
self.assertEqual(True, svc.is_correct())
svc.max_check_attempts = max_check_attempts
###
### Now special cases
###
# no check command
check_command = svc.check_command
del svc.check_command
self.assertEqual(False, svc.is_correct())
svc.check_command = check_command
self.assertEqual(True, svc.is_correct())
# no notification_interval
notification_interval = svc.notification_interval
del svc.notification_interval
self.assertEqual(False, svc.is_correct())
svc.notification_interval = notification_interval
self.assertEqual(True, svc.is_correct())
# Look for set/unset impacted states (unknown)
def test_impact_state(self):
svc = self.get_svc()
ori_state = svc.state
ori_state_id = svc.state_id
svc.set_impact_state()
self.assertEqual('UNKNOWN', svc.state)
self.assertEqual(3, svc.state_id)
svc.unset_impact_state()
self.assertEqual(ori_state, svc.state)
self.assertEqual(ori_state_id, svc.state_id)
# Look for display name setting
def test_display_name(self):
svc = self.get_svc()
self.assertEqual('test_ok_0', svc.display_name)
def test_states_from_exit_status(self):
svc = self.get_svc()
# First OK
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual('OK', svc.state)
self.assertEqual(0, svc.state_id)
self.assertEqual(True, svc.is_state('OK'))
self.assertEqual(True, svc.is_state('o'))
# Then warning
self.scheduler_loop(1, [[svc, 1, 'WARNING']])
self.assertEqual('WARNING', svc.state)
self.assertEqual(1, svc.state_id)
self.assertEqual(True, svc.is_state('WARNING'))
self.assertEqual(True, svc.is_state('w'))
# Then Critical
self.scheduler_loop(1, [[svc, 2, 'CRITICAL']])
self.assertEqual('CRITICAL', svc.state)
self.assertEqual(2, svc.state_id)
self.assertEqual(True, svc.is_state('CRITICAL'))
self.assertEqual(True, svc.is_state('c'))
# And unknown
self.scheduler_loop(1, [[svc, 3, 'UNKNOWN']])
self.assertEqual('UNKNOWN', svc.state)
self.assertEqual(3, svc.state_id)
self.assertEqual(True, svc.is_state('UNKNOWN'))
self.assertEqual(True, svc.is_state('u'))
# And something else :)
self.scheduler_loop(1, [[svc, 99, 'WTF return :)']])
self.assertEqual('CRITICAL', svc.state)
self.assertEqual(2, svc.state_id)
self.assertEqual(True, svc.is_state('CRITICAL'))
self.assertEqual(True, svc.is_state('c'))
def test_business_impact_value(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
# This service inherit the improtance value from his father, 5
self.assertEqual(5, svc.business_impact)
# Look if the service is in the servicegroup
def test_servicegroup(self):
sg = self.sched.servicegroups.find_by_name("servicegroup_01")
self.assertIsNot(sg, None)
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
self.assertIn(svc, sg.members)
self.assertIn(sg.get_name(), [sg.get_name() for sg in svc.servicegroups])
# Look at the good of the last_hard_state_change
def test_service_last_hard_state(self):
self.print_header()
# We want an eventhandelr (the perfdata command) to be put in the actions dict
# after we got a service check
now = time.time()
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
# We do not want to be just a string but a real command
self.scheduler_loop(1, [[svc, 0, 'OK | bibi=99%']])
print("FUCK", svc.last_hard_state_change)
orig = svc.last_hard_state_change
self.assertEqual('OK', svc.last_hard_state)
# now still ok
self.scheduler_loop(1, [[svc, 0, 'OK | bibi=99%']])
self.assertEqual(orig, svc.last_hard_state_change)
self.assertEqual('OK', svc.last_hard_state)
# now error but still SOFT
self.scheduler_loop(1, [[svc, 2, 'CRITICAL | bibi=99%']])
print("FUCK", svc.state_type)
self.assertEqual(orig, svc.last_hard_state_change)
self.assertEqual('OK', svc.last_hard_state)
# now go hard!
time.sleep(2)
now = int(time.time())
self.assertLess(svc.last_hard_state_change, now)
self.scheduler_loop(1, [[svc, 2, 'CRITICAL | bibi=99%']])
print("FUCK", svc.state_type)
self.assertGreaterEqual(svc.last_hard_state_change, now)
self.assertEqual('CRITICAL', svc.last_hard_state)
print("Last hard state id", svc.last_hard_state_id)
self.assertEqual(2, svc.last_hard_state_id)
# Check if the autoslots are fill like it should
def test_autoslots(self):
svc = self.get_svc()
self.assertNotIn("check_period", svc.__dict__)
# Check if the parent/childs dependencies are fill like it should
def test_parent_child_dep_list(self):
svc = self.get_svc()
# Look if our host is a parent
self.assertIn(svc.host, svc.parent_dependencies)
# and if we are a child of it
self.assertIn(svc, svc.host.child_dependencies)
if __name__ == '__main__':
unittest.main()
| 8,313
|
Python
|
.py
| 185
| 37.356757
| 92
| 0.634779
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,355
|
__import_shinken.py
|
shinken-solutions_shinken/test/__import_shinken.py
|
# -*- coding: utf-8 ; mode: python -*-
#
# Copyright (C) 2012:
# Hartmut Goebel <h.goebel@crazy-compilers.com>
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
"""
Helper module for importing the shinken library from the (uninstalled)
test-suite.
If importing shinken fails, try to load from parent directory to
support running the test-suite without installation.
This does not manipulate sys.path, but uses lower-level Python modules
for looking up and loading the module `shinken` from the directory one
level above this module.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
try:
import shinken
except ImportError:
import imp, os
# For security reasons, try not to load `shinken` from parent
# directory when running as root.
if True or not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('shinken', *imp.find_module('shinken',
[os.path.dirname(os.path.dirname(os.path.abspath(__file__)))]))
else:
# running as root: re-raise the exception
raise
| 1,698
|
Python
|
.py
| 41
| 38.780488
| 82
| 0.746061
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,356
|
test_utf8_log.py
|
shinken-solutions_shinken/test/test_utf8_log.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
import six
from shinken_test import *
from shinken.log import logger
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_1r_1h_1s.cfg')
# Try to raise an utf8 log message
def test_utf8log(self):
sutf = 'h\351h\351' # Latin Small Letter E with acute in Latin-1
logger.info(sutf)
sutf8 = 'I love myself $£¤' # dollar, pound, currency
logger.info(sutf8)
s = six.unichr(40960) + 'abcd' + six.unichr(1972)
logger.info(s)
if __name__ == '__main__':
unittest.main()
| 1,564
|
Python
|
.py
| 41
| 35.121951
| 82
| 0.718915
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,357
|
test_missing_timeperiod.py
|
shinken-solutions_shinken/test/test_missing_timeperiod.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestMissingTimeperiod(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_missing_timeperiod.cfg')
def test_dummy(self):
self.assertFalse(self.conf.conf_is_correct)
if __name__ == '__main__':
unittest.main()
| 1,254
|
Python
|
.py
| 31
| 38.258065
| 82
| 0.757002
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,358
|
test_define_with_space.py
|
shinken-solutions_shinken/test/test_define_with_space.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestDefineWithSpaces(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_define_with_space.cfg')
# We got a problem with define host for example, the type read was "" and not host
def testdefine_with_spaces(self):
host = self.sched.hosts.find_by_name("test_host_0")
self.assertIsNot(host, None)
if __name__ == '__main__':
unittest.main()
| 1,399
|
Python
|
.py
| 33
| 39.909091
| 89
| 0.745763
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,359
|
test_objects_and_notifways.py
|
shinken-solutions_shinken/test/test_objects_and_notifways.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestObjectsAndNotifWays(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_objects_and_notifways.cfg')
# We got strange "objects" for some contacts property when we are using notif ways
# and asking for broks. Search why
def test_dummy(self):
c_normal = self.sched.contacts.find_by_name("test_contact")
self.assertIsNot(c_normal, None)
c_nw = self.sched.contacts.find_by_name("test_contact_nw")
self.assertIsNot(c_nw, None)
b = c_normal.get_initial_status_brok()
#b.prepare()
print("B normal", b)
self.assertEqual(['d', 'u', 'r', 'f', 's'], b.data['host_notification_options'])
b2 = c_nw.get_initial_status_brok()
#b2.prepare()
print("B nw", b2)
self.assertEqual([u''], b2.data['host_notification_options'])
if __name__ == '__main__':
unittest.main()
| 1,895
|
Python
|
.py
| 44
| 39.045455
| 88
| 0.705755
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,360
|
test_business_correlator_expand_expression.py
|
shinken-solutions_shinken/test/test_business_correlator_expand_expression.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test hostgroups and regex expressions expansion in
# business rules.
#
from __future__ import absolute_import, division, print_function, unicode_literals
import re
from shinken_test import (
unittest,
ShinkenTest,
)
# Set this variable False to disable profiling test
PROFILE_BP_RULE_RE_PROCESSING = False
class TestBusinesscorrelExpand(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_business_correlator_expand_expression.cfg')
def test_hostgroup_expansion_bprule_simple_host_srv(self):
for name in ("bprule_00", "bprule_01", "bprule_02", "bprule_03", "bprule_04", "bprule_05", "bprule_06"):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", name)
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
bp_rule = svc_cor.business_rule
self.assertEqual('&', bp_rule.operand)
self.assertIs(False, bp_rule.not_value)
self.assertEqual(('2', '2', '2'), bp_rule.of_values)
srv1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
srv2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv1")
sons = bp_rule.sons
self.assertEqual(2, len(sons))
self.assertEqual('service', sons[0].operand)
self.assertEqual('service', sons[1].operand)
self.assertIn(srv1, (sons[0].sons[0], sons[1].sons[0]))
self.assertIn(srv2, (sons[0].sons[0], sons[1].sons[0]))
def test_hostgroup_expansion_bprule_simple_xof_host_srv(self):
for name in ("bprule_10", "bprule_11", "bprule_12", "bprule_13", "bprule_14", "bprule_15", "bprule_16", "bprule_17"):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", name)
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
bp_rule = svc_cor.business_rule
self.assertEqual('of:', bp_rule.operand)
self.assertIs(False, bp_rule.not_value)
self.assertEqual(('1', '2', '2'), bp_rule.of_values)
srv1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
srv2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv1")
sons = bp_rule.sons
self.assertEqual(2, len(sons))
self.assertEqual('service', sons[0].operand)
self.assertEqual('service', sons[1].operand)
self.assertIn(srv1, (sons[0].sons[0], sons[1].sons[0]))
self.assertIn(srv2, (sons[0].sons[0], sons[1].sons[0]))
def test_hostgroup_expansion_bprule_combined_and(self):
for name in ("bprule_20", "bprule_21", "bprule_22", "bprule_23", "bprule_24", "bprule_25", "bprule_26"):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", name)
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
bp_rule = svc_cor.business_rule
self.assertEqual('&', bp_rule.operand)
self.assertIs(False, bp_rule.not_value)
self.assertEqual(('2', '2', '2'), bp_rule.of_values)
sons = bp_rule.sons
self.assertEqual(2, len(sons))
for son in sons:
self.assertEqual('&', son.operand)
self.assertIs(False, son.not_value)
self.assertEqual(('2', '2', '2'), son.of_values)
self.assertEqual(2, len(son.sons))
self.assertEqual('service', son.sons[0].operand)
self.assertEqual('service', son.sons[1].operand)
hst1_srv1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
hst2_srv1 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv1")
hst1_srv2 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv2")
hst2_srv2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv2")
self.assertIn(hst1_srv1, (sons[0].sons[0].sons[0], sons[0].sons[1].sons[0]))
self.assertIn(hst2_srv1, (sons[0].sons[0].sons[0], sons[0].sons[1].sons[0]))
self.assertIn(hst1_srv2, (sons[1].sons[0].sons[0], sons[1].sons[1].sons[0]))
self.assertIn(hst2_srv2, (sons[1].sons[0].sons[0], sons[1].sons[1].sons[0]))
def test_hostgroup_expansion_bprule_combined_or(self):
for name in ("bprule_30", "bprule_31", "bprule_32", "bprule_33", "bprule_34", "bprule_35", "bprule_36"):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", name)
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
bp_rule = svc_cor.business_rule
self.assertEqual('|', bp_rule.operand)
self.assertIs(False, bp_rule.not_value)
self.assertEqual(('2', '2', '2'), bp_rule.of_values)
sons = bp_rule.sons
self.assertEqual(2, len(sons))
for son in sons:
self.assertEqual('&', son.operand)
self.assertIs(False, son.not_value)
self.assertEqual(('2', '2', '2'), son.of_values)
self.assertEqual(2, len(son.sons))
self.assertEqual('service', son.sons[0].operand)
self.assertEqual('service', son.sons[1].operand)
hst1_srv1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
hst2_srv1 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv1")
hst1_srv2 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv2")
hst2_srv2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv2")
self.assertIn(hst1_srv1, (sons[0].sons[0].sons[0], sons[0].sons[1].sons[0]))
self.assertIn(hst2_srv1, (sons[0].sons[0].sons[0], sons[0].sons[1].sons[0]))
self.assertIn(hst1_srv2, (sons[1].sons[0].sons[0], sons[1].sons[1].sons[0]))
self.assertIn(hst2_srv2, (sons[1].sons[0].sons[0], sons[1].sons[1].sons[0]))
def test_hostgroup_expansion_bprule_simple_hosts(self):
for name in ("bprule_40", "bprule_41", "bprule_42", "bprule_43"):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", name)
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
bp_rule = svc_cor.business_rule
self.assertEqual('&', bp_rule.operand)
self.assertIs(False, bp_rule.not_value)
self.assertEqual(('2', '2', '2'), bp_rule.of_values)
hst1 = self.sched.hosts.find_by_name("test_host_01")
hst2 = self.sched.hosts.find_by_name("test_host_02")
sons = bp_rule.sons
self.assertEqual(2, len(sons))
self.assertEqual('host', sons[0].operand)
self.assertEqual('host', sons[1].operand)
self.assertIn(hst1, (sons[0].sons[0], sons[1].sons[0]))
self.assertIn(hst2, (sons[0].sons[0], sons[1].sons[0]))
def test_hostgroup_expansion_bprule_xof_hosts(self):
for name in ("bprule_50", "bprule_51", "bprule_52", "bprule_53", "bprule_54"):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", name)
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
bp_rule = svc_cor.business_rule
self.assertEqual('of:', bp_rule.operand)
self.assertIs(False, bp_rule.not_value)
self.assertEqual(('1', '2', '2'), bp_rule.of_values)
hst1 = self.sched.hosts.find_by_name("test_host_01")
hst2 = self.sched.hosts.find_by_name("test_host_02")
sons = bp_rule.sons
self.assertEqual(2, len(sons))
self.assertEqual('host', sons[0].operand)
self.assertEqual('host', sons[1].operand)
self.assertIn(hst1, (sons[0].sons[0], sons[1].sons[0]))
self.assertIn(hst2, (sons[0].sons[0], sons[1].sons[0]))
def test_hostgroup_expansion_bprule_same_host_srv(self):
for name in ("bprule_60", "bprule_61"):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("test_host_01", name)
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
bp_rule = svc_cor.business_rule
self.assertEqual('&', bp_rule.operand)
self.assertIs(False, bp_rule.not_value)
self.assertEqual(('2', '2', '2'), bp_rule.of_values)
srv1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
srv2 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv2")
sons = bp_rule.sons
self.assertEqual(2, len(sons))
self.assertEqual('service', sons[0].operand)
self.assertEqual('service', sons[1].operand)
self.assertIn(srv1, (sons[0].sons[0], sons[1].sons[0]))
self.assertIn(srv2, (sons[0].sons[0], sons[1].sons[0]))
def test_hostgroup_expansion_bprule_xof_same_host_srv(self):
for name in ("bprule_70", "bprule_71"):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("test_host_01", name)
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
bp_rule = svc_cor.business_rule
self.assertEqual('of:', bp_rule.operand)
self.assertIs(False, bp_rule.not_value)
self.assertEqual(('1', '2', '2'), bp_rule.of_values)
srv1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
srv2 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv2")
sons = bp_rule.sons
self.assertEqual(2, len(sons))
self.assertEqual('service', sons[0].operand)
self.assertEqual('service', sons[1].operand)
self.assertIn(srv1, (sons[0].sons[0], sons[1].sons[0]))
self.assertIn(srv2, (sons[0].sons[0], sons[1].sons[0]))
def test_macro_expansion_bprule_no_macro(self):
# Tests macro expansion
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", "bprule_no_macro")
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
self.assertEqual("1 of: test_host_01,srv1 & test_host_02,srv2", svc_cor.processed_business_rule)
bp_rule = svc_cor.business_rule
self.assertEqual('of:', bp_rule.operand)
self.assertEqual(('1', '2', '2'), bp_rule.of_values)
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv2")
# Setting dependent services status
self.scheduler_loop(1, [
[svc1, 0, 'UP | value1=1 value2=2'],
[svc2, 0, 'UP | value1=1 value2=2']])
self.assertEqual('OK', svc1.state)
self.assertEqual('HARD', svc1.state_type)
self.assertEqual('OK', svc2.state)
self.assertEqual('HARD', svc2.state_type)
self.scheduler_loop(1, [[svc1, 2, 'CRITICAL | value1=1 value2=2']])
self.assertEqual('CRITICAL', svc1.state)
self.assertEqual('HARD', svc1.state_type)
# Forces business rule evaluation.
self.scheduler_loop(2, [[svc_cor, None, None]], do_sleep=True)
# Business rule should not have been re-evaluated (no macro in the
# bp_rule)
self.assertIs(bp_rule, svc_cor.business_rule)
bp_rule = svc_cor.business_rule
self.assertEqual(0, bp_rule.get_state())
self.assertEqual(0, svc_cor.last_hard_state_id)
def test_macro_expansion_bprule_macro_expand(self):
# Tests macro expansion
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", "bprule_macro_expand")
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
self.assertEqual("1 of: test_host_01,srv1 & test_host_02,srv2", svc_cor.processed_business_rule)
bp_rule = svc_cor.business_rule
self.assertEqual('of:', bp_rule.operand)
self.assertEqual(('1', '2', '2'), bp_rule.of_values)
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv2")
# Setting dependent services status
self.scheduler_loop(1, [
[svc1, 0, 'UP | value1=1 value2=2'],
[svc2, 0, 'UP | value1=1 value2=2']])
self.assertEqual('OK', svc1.state)
self.assertEqual('HARD', svc1.state_type)
self.assertEqual('OK', svc2.state)
self.assertEqual('HARD', svc2.state_type)
self.scheduler_loop(1, [[svc1, 2, 'CRITICAL | value1=1 value2=2']])
self.assertEqual('CRITICAL', svc1.state)
self.assertEqual('HARD', svc1.state_type)
# Forces business rule evaluation.
self.scheduler_loop(2, [[svc_cor, None, None]], do_sleep=True)
# Business rule should not have been re-evaluated (macro did not change
# value)
self.assertIs(bp_rule, svc_cor.business_rule)
bp_rule = svc_cor.business_rule
self.assertEqual(0, bp_rule.get_state())
self.assertEqual(0, svc_cor.last_hard_state_id)
def test_macro_expansion_bprule_macro_modulated(self):
# Tests macro modulation
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy_modulated", "bprule_macro_modulated")
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
self.assertEqual("2 of: test_host_01,srv1 & test_host_02,srv2", svc_cor.processed_business_rule)
bp_rule = svc_cor.business_rule
self.assertEqual('of:', bp_rule.operand)
self.assertEqual(('2', '2', '2'), bp_rule.of_values)
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv2")
# Setting dependent services status
self.scheduler_loop(1, [
[svc1, 0, 'UP | value1=1 value2=2'],
[svc2, 0, 'UP | value1=1 value2=2']])
self.assertEqual('OK', svc1.state)
self.assertEqual('HARD', svc1.state_type)
self.assertEqual('OK', svc2.state)
self.assertEqual('HARD', svc2.state_type)
self.scheduler_loop(1, [[svc1, 2, 'CRITICAL | value1=1 value2=2']])
self.assertEqual('CRITICAL', svc1.state)
self.assertEqual('HARD', svc1.state_type)
# Forces business rule evaluation.
self.scheduler_loop(2, [[svc_cor, None, None]], do_sleep=True)
# Business rule should not have been re-evaluated (macro did not change
# value)
self.assertIs(bp_rule, svc_cor.business_rule)
bp_rule = svc_cor.business_rule
self.assertEqual(2, bp_rule.get_state())
self.assertEqual(2, svc_cor.last_hard_state_id)
# Tests modulated value
mod = self.sched.macromodulations.find_by_name("xof_modulation")
mod.customs['_XOF'] = '1'
# Forces business rule evaluation.
self.scheduler_loop(2, [[svc_cor, None, None]], do_sleep=True)
self.assertEqual("1 of: test_host_01,srv1 & test_host_02,srv2", svc_cor.processed_business_rule)
self.assertIsNot(svc_cor.business_rule, bp_rule)
bp_rule = svc_cor.business_rule
self.assertEqual('of:', bp_rule.operand)
self.assertEqual(('1', '2', '2'), bp_rule.of_values)
self.assertEqual(0, bp_rule.get_state())
self.assertEqual(0, svc_cor.last_hard_state_id)
# Tests wrongly written macro modulation (inserts invalid string)
mod.customs['_XOF'] = 'fake'
# Forces business rule evaluation.
self.scheduler_loop(2, [[svc_cor, None, None]], do_sleep=True)
# Business rule should have been re-evaluated (macro was modulated)
self.assertIs(bp_rule, svc_cor.business_rule)
self.assertEqual(3, svc_cor.last_hard_state_id)
self.assertTrue(svc_cor.output.startswith("Error while re-evaluating business rule"))
def test_macro_expansion_bprule_macro_profile(self):
if PROFILE_BP_RULE_RE_PROCESSING is False:
return
import cProfile as profile
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv2")
# Setting dependent services status
self.scheduler_loop(1, [
[svc1, 0, 'UP | value1=1 value2=2'],
[svc2, 0, 'UP | value1=1 value2=2']], verbose=False)
self.assertEqual('OK', svc1.state)
self.assertEqual('HARD', svc1.state_type)
self.assertEqual('OK', svc2.state)
self.assertEqual('HARD', svc2.state_type)
self.scheduler_loop(1, [[svc1, 2, 'CRITICAL | value1=1 value2=2']], verbose=False)
self.assertEqual('CRITICAL', svc1.state)
self.assertEqual('HARD', svc1.state_type)
print("Profiling without macro")
def profile_bp_rule_without_macro():
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", "bprule_no_macro")
for i in range(1000):
self.scheduler_loop(2, [[svc_cor, None, None]], do_sleep=True, verbose=False)
profile.runctx('profile_bp_rule_without_macro()', globals(), locals())
print("Profiling with macro")
def profile_bp_rule_macro_expand():
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", "bprule_macro_expand")
for i in range(1000):
self.scheduler_loop(2, [[svc_cor, None, None]], do_sleep=True, verbose=False)
profile.runctx('profile_bp_rule_macro_expand()', globals(), locals())
print("Profiling with macro modulation")
def profile_bp_rule_macro_modulated():
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy_modulated", "bprule_macro_modulated")
for i in range(1000):
self.scheduler_loop(2, [[svc_cor, None, None]], do_sleep=True, verbose=False)
profile.runctx('profile_bp_rule_macro_modulated()', globals(), locals())
class TestConfigBroken(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_business_correlator_expand_expression_broken.cfg')
def test_hostgroup_expansion_errors(self):
self.assertFalse(self.conf.conf_is_correct)
# Get the arbiter's log broks
#[b.prepare() for b in self.broks]
logs = [b.data['log'] for b in self.broks if b.type == 'log']
self.assertEqual(1, len([log for log in logs if re.search('Business rule uses invalid regex', log)]) )
self.assertEqual(3, len([log for log in logs if re.search('Business rule got an empty result', log)]) )
if __name__ == '__main__':
unittest.main()
| 20,299
|
Python
|
.py
| 345
| 48.527536
| 125
| 0.627505
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,361
|
test_servicedependency_complexes.py
|
shinken-solutions_shinken/test/test_servicedependency_complexes.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_servicedependency_complexes.cfg')
def test_dummy(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
for s in self.sched.services:
print(s.get_full_name())
NRPE = self.sched.services.find_srv_by_name_and_hostname("myspecifichost", "NRPE")
self.assertIsNot(NRPE, None)
Load = self.sched.services.find_srv_by_name_and_hostname("myspecifichost", "Load")
self.assertIsNot(Load, None)
print(Load.act_depend_of)
self.assertIn(NRPE, [e[0] for e in Load.act_depend_of])
if __name__ == '__main__':
unittest.main()
| 1,748
|
Python
|
.py
| 42
| 37.547619
| 90
| 0.716559
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,362
|
test_not_hostname.py
|
shinken-solutions_shinken/test/test_not_hostname.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
import time
from shinken_test import unittest, ShinkenTest
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_not_hostname.cfg')
def test_not_hostname_in_service(self):
# The service is apply with a host_group on "test_host_0","test_host_1"
# but have a host_name with !"test_host_1" so there will be just "test_host_0"
# defined on the end
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
svc_not = self.sched.services.find_srv_by_name_and_hostname("test_host_1", "test_ok_0")
# Check if the service for the good host is here
self.assertIsNot(svc, None)
# check if the service for the not one (!) is not here
self.assertIs(None, svc_not)
if __name__ == '__main__':
unittest.main()
| 2,301
|
Python
|
.py
| 50
| 41.36
| 95
| 0.696429
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,363
|
test_dispatcher.py
|
shinken-solutions_shinken/test/test_dispatcher.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class GoodArbiter(ArbiterLink):
# To lie about satellites
def ping(self):
print("Dummy OK for", self.get_name())
self.set_alive()
def have_conf(self, i):
return True
def do_not_run(self):
pass
class GoodScheduler(SchedulerLink):
# To lie about satellites
def ping(self):
print("Dummy OK for", self.get_name())
self.set_alive()
def have_conf(self, i):
return True
def put_conf(self, conf):
return True
class BadScheduler(SchedulerLink):
def ping(self):
print("Dummy bad ping", self.get_name())
self.add_failed_check_attempt()
def have_conf(self, i):
return False
class GoodPoller(PollerLink):
# To lie about satellites
def ping(self):
print("Dummy OK for", self.get_name())
self.set_alive()
def put_conf(self, conf):
return True
class BadPoller(PollerLink):
def ping(self):
print("Dummy bad ping", self.get_name())
self.add_failed_check_attempt()
class GoodReactionner(ReactionnerLink):
# To lie about satellites
def ping(self):
print("Dummy OK for", self.get_name())
self.set_alive()
def put_conf(self, conf):
return True
class BadReactionner(ReactionnerLink):
def ping(self):
print("Dummy bad ping", self.get_name())
self.add_failed_check_attempt()
class GoodBroker(BrokerLink):
# To lie about satellites
def ping(self):
print("Dummy OK for", self.get_name())
self.set_alive()
def put_conf(self, conf):
return True
class BadBroker(BrokerLink):
def ping(self):
print("Dummy bad ping", self.get_name())
self.add_failed_check_attempt()
class TestDispatcher(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_dispatcher.cfg')
def test_simple_dispatch(self):
for r in self.conf.realms:
print(r.get_name())
r = self.conf.realms.find_by_name('All')
print("The dispatcher", self.dispatcher)
# dummy for the arbiter
for a in self.conf.arbiters:
a.__class__ = GoodArbiter
elts_types = ['schedulers', 'pollers', 'reactionners', 'brokers', 'receivers']
for t in elts_types:
lst = getattr(self.conf, t)
for s in lst:
print("TAG s", s)
s.realm = r
print("Preparing schedulers")
scheduler1 = self.conf.schedulers.find_by_name('scheduler-all-1')
self.assertIsNot(scheduler1, None)
scheduler1.__class__ = GoodScheduler
scheduler2 = self.conf.schedulers.find_by_name('scheduler-all-2')
self.assertIsNot(scheduler2, None)
scheduler2.__class__ = BadScheduler
print("Preparing pollers")
poller1 = self.conf.pollers.find_by_name('poller-all-1')
self.assertIsNot(poller1, None)
poller1.__class__ = GoodPoller
poller2 = self.conf.pollers.find_by_name('poller-all-2')
self.assertIsNot(poller2, None)
poller2.__class__ = BadPoller
print("Preparing reactionners")
reactionner1 = self.conf.reactionners.find_by_name('reactionner-all-1')
self.assertIsNot(reactionner1, None)
reactionner1.__class__ = GoodReactionner
reactionner2 = self.conf.reactionners.find_by_name('reactionner-all-2')
self.assertIsNot(reactionner2, None)
reactionner2.__class__ = BadReactionner
print("Preparing brokers")
broker1 = self.conf.brokers.find_by_name('broker-all-1')
self.assertIsNot(broker1, None)
broker1.__class__ = GoodBroker
broker2 = self.conf.brokers.find_by_name('broker-all-2')
self.assertIsNot(broker2, None)
broker2.__class__ = BadBroker
# Ping all elements. Should have 1 as OK, 2 as
# one bad attempt (3 max)
self.dispatcher.check_alive()
# Check good values
self.assertEqual(True, scheduler1.alive)
self.assertEqual(0, scheduler1.attempt)
self.assertEqual(True, scheduler1.reachable)
# still alive, just unreach
self.assertEqual(True, scheduler2.alive)
self.assertEqual(1, scheduler2.attempt)
self.assertEqual(False, scheduler2.reachable)
# and others satellites too
self.assertEqual(True, poller1.alive)
self.assertEqual(0, poller1.attempt)
self.assertEqual(True, poller1.reachable)
# still alive, just unreach
self.assertEqual(True, poller2.alive)
self.assertEqual(1, poller2.attempt)
self.assertEqual(False, poller2.reachable)
# and others satellites too
self.assertEqual(True, reactionner1.alive)
self.assertEqual(0, reactionner1.attempt)
self.assertEqual(True, reactionner1.reachable)
# still alive, just unreach
self.assertEqual(True, reactionner2.alive)
self.assertEqual(1, reactionner2.attempt)
self.assertEqual(False, reactionner2.reachable)
# and others satellites too
self.assertEqual(True, broker1.alive)
self.assertEqual(0, broker1.attempt)
self.assertEqual(True, broker1.reachable)
# still alive, just unreach
self.assertEqual(True, broker2.alive)
self.assertEqual(1, broker2.attempt)
self.assertEqual(False, broker2.reachable)
### Now add another attempt, still alive, but attemp=2/3
print("CheckAlive " * 10)
# We reset check time for the test
elts = [scheduler1, scheduler2, poller1, poller2, broker1, broker2, reactionner1, reactionner2]
for i in elts:
i.last_check = 0.0
self.dispatcher.check_alive()
# Check good values
self.assertEqual(True, scheduler1.alive)
self.assertEqual(0, scheduler1.attempt)
self.assertEqual(True, scheduler1.reachable)
# still alive, just unreach
self.assertEqual(True, scheduler2.alive)
self.assertEqual(2, scheduler2.attempt)
self.assertEqual(False, scheduler2.reachable)
# and others satellites too
self.assertEqual(True, poller1.alive)
self.assertEqual(0, poller1.attempt)
self.assertEqual(True, poller1.reachable)
# still alive, just unreach
self.assertEqual(True, poller2.alive)
self.assertEqual(2, poller2.attempt)
self.assertEqual(False, poller2.reachable)
# and others satellites too
self.assertEqual(True, reactionner1.alive)
self.assertEqual(0, reactionner1.attempt)
self.assertEqual(True, reactionner1.reachable)
# still alive, just unreach
self.assertEqual(True, reactionner2.alive)
self.assertEqual(2, reactionner2.attempt)
self.assertEqual(False, reactionner2.reachable)
# and others satellites too
self.assertEqual(True, broker1.alive)
self.assertEqual(0, broker1.attempt)
self.assertEqual(True, broker1.reachable)
# still alive, just unreach
self.assertEqual(True, broker2.alive)
self.assertEqual(2, broker2.attempt)
self.assertEqual(False, broker2.reachable)
### Now we get BAD, We go DEAD for N2!
print("CheckAlive " * 10)
# We reset check time for the test
elts = [scheduler1, scheduler2, poller1, poller2, broker1, broker2, reactionner1, reactionner2]
for i in elts:
i.last_check = 0.0
self.dispatcher.check_alive()
# Check good values
self.assertEqual(True, scheduler1.alive)
self.assertEqual(0, scheduler1.attempt)
self.assertEqual(True, scheduler1.reachable)
# still alive, just unreach
self.assertEqual(False, scheduler2.alive)
self.assertEqual(3, scheduler2.attempt)
self.assertEqual(False, scheduler2.reachable)
# and others satellites too
self.assertEqual(True, poller1.alive)
self.assertEqual(0, poller1.attempt)
self.assertEqual(True, poller1.reachable)
# still alive, just unreach
self.assertEqual(False, poller2.alive)
self.assertEqual(3, poller2.attempt)
self.assertEqual(False, poller2.reachable)
# and others satellites too
self.assertEqual(True, reactionner1.alive)
self.assertEqual(0, reactionner1.attempt)
self.assertEqual(True, reactionner1.reachable)
# still alive, just unreach
self.assertEqual(False, reactionner2.alive)
self.assertEqual(3, reactionner2.attempt)
self.assertEqual(False, reactionner2.reachable)
# and others satellites too
self.assertEqual(True, broker1.alive)
self.assertEqual(0, broker1.attempt)
self.assertEqual(True, broker1.reachable)
# still alive, just unreach
self.assertEqual(False, broker2.alive)
self.assertEqual(3, broker2.attempt)
self.assertEqual(False, broker2.reachable)
# Now we check how we should dispatch confs
self.dispatcher.check_dispatch()
# the conf should not be in a good shape
self.assertEqual(False, self.dispatcher.dispatch_ok)
# Now we really dispatch them!
self.dispatcher.dispatch()
self.assert_any_log_match('Dispatch OK of conf in scheduler scheduler-all-1')
self.assert_any_log_match('Dispatch OK of configuration 0 to reactionner reactionner-all-1')
self.assert_any_log_match('Dispatch OK of configuration 0 to poller poller-all-1')
self.assert_any_log_match('Dispatch OK of configuration 0 to broker broker-all-1')
self.clear_logs()
# And look if we really dispatch conf as we should
for r in self.conf.realms:
for cfg in r.confs.values():
self.assertEqual(True, cfg.is_assigned)
self.assertEqual(scheduler1, cfg.assigned_to)
class TestDispatcherMultiBroker(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_dispatcher_multibrokers.cfg')
def test_simple_dispatch(self):
print("The dispatcher", self.dispatcher)
# dummy for the arbiter
for a in self.conf.arbiters:
a.__class__ = GoodArbiter
print("Preparing schedulers")
scheduler1 = self.conf.schedulers.find_by_name('scheduler-all-1')
self.assertIsNot(scheduler1, None)
scheduler1.__class__ = GoodScheduler
scheduler2 = self.conf.schedulers.find_by_name('scheduler-all-2')
self.assertIsNot(scheduler2, None)
scheduler2.__class__ = GoodScheduler
print("Preparing pollers")
poller1 = self.conf.pollers.find_by_name('poller-all-1')
self.assertIsNot(poller1, None)
poller1.__class__ = GoodPoller
poller2 = self.conf.pollers.find_by_name('poller-all-2')
self.assertIsNot(poller2, None)
poller2.__class__ = BadPoller
print("Preparing reactionners")
reactionner1 = self.conf.reactionners.find_by_name('reactionner-all-1')
self.assertIsNot(reactionner1, None)
reactionner1.__class__ = GoodReactionner
reactionner2 = self.conf.reactionners.find_by_name('reactionner-all-2')
self.assertIsNot(reactionner2, None)
reactionner2.__class__ = BadReactionner
print("Preparing brokers")
broker1 = self.conf.brokers.find_by_name('broker-all-1')
self.assertIsNot(broker1, None)
broker1.__class__ = GoodBroker
broker2 = self.conf.brokers.find_by_name('broker-all-2')
self.assertIsNot(broker2, None)
broker2.__class__ = GoodBroker
# Ping all elements. Should have 1 as OK, 2 as
# one bad attempt (3 max)
self.dispatcher.check_alive()
# Check good values
self.assertEqual(True, scheduler1.alive)
self.assertEqual(0, scheduler1.attempt)
self.assertEqual(True, scheduler1.reachable)
# still alive, just unreach
self.assertEqual(True, scheduler2.alive)
self.assertEqual(0, scheduler2.attempt)
self.assertEqual(True, scheduler2.reachable)
# and others satellites too
self.assertEqual(True, poller1.alive)
self.assertEqual(0, poller1.attempt)
self.assertEqual(True, poller1.reachable)
# still alive, just unreach
self.assertEqual(True, poller2.alive)
self.assertEqual(1, poller2.attempt)
self.assertEqual(False, poller2.reachable)
# and others satellites too
self.assertEqual(True, reactionner1.alive)
self.assertEqual(0, reactionner1.attempt)
self.assertEqual(True, reactionner1.reachable)
# still alive, just unreach
self.assertEqual(True, reactionner2.alive)
self.assertEqual(1, reactionner2.attempt)
self.assertEqual(False, reactionner2.reachable)
# and others satellites too
self.assertEqual(True, broker1.alive)
self.assertEqual(0, broker1.attempt)
self.assertEqual(True, broker1.reachable)
# still alive, just unreach
self.assertEqual(True, broker2.alive)
self.assertEqual(0, broker2.attempt)
self.assertEqual(True, broker2.reachable)
### Now add another attempt, still alive, but attemp=2/3
print("CheckAlive " * 10)
# We reset check time for the test
elts = [scheduler1, scheduler2, poller1, poller2, broker1, broker2, reactionner1, reactionner2]
for i in elts:
i.last_check = 0.0
self.dispatcher.check_alive()
# Check good values
self.assertEqual(True, scheduler1.alive)
self.assertEqual(0, scheduler1.attempt)
self.assertEqual(True, scheduler1.reachable)
# still alive, just unreach
self.assertEqual(True, scheduler2.alive)
self.assertEqual(0, scheduler2.attempt)
self.assertEqual(True, scheduler2.reachable)
# and others satellites too
self.assertEqual(True, poller1.alive)
self.assertEqual(0, poller1.attempt)
self.assertEqual(True, poller1.reachable)
# still alive, just unreach
self.assertEqual(True, poller2.alive)
self.assertEqual(2, poller2.attempt)
self.assertEqual(False, poller2.reachable)
# and others satellites too
self.assertEqual(True, reactionner1.alive)
self.assertEqual(0, reactionner1.attempt)
self.assertEqual(True, reactionner1.reachable)
# still alive, just unreach
self.assertEqual(True, reactionner2.alive)
self.assertEqual(2, reactionner2.attempt)
self.assertEqual(False, reactionner2.reachable)
# and others satellites too
self.assertEqual(True, broker1.alive)
self.assertEqual(0, broker1.attempt)
self.assertEqual(True, broker1.reachable)
# still alive, just unreach
self.assertEqual(True, broker2.alive)
self.assertEqual(0, broker2.attempt)
self.assertEqual(True, broker2.reachable)
### Now we get BAD, We go DEAD for N2!
print("CheckAlive " * 10)
# We reset check time for the test
elts = [scheduler1, scheduler2, poller1, poller2, broker1, broker2, reactionner1, reactionner2]
for i in elts:
i.last_check = 0.0
self.dispatcher.check_alive()
# Check good values
self.assertEqual(True, scheduler1.alive)
self.assertEqual(0, scheduler1.attempt)
self.assertEqual(True, scheduler1.reachable)
# still alive, just unreach
self.assertEqual(True, scheduler2.alive)
self.assertEqual(0, scheduler2.attempt)
self.assertEqual(True, scheduler2.reachable)
# and others satellites too
self.assertEqual(True, poller1.alive)
self.assertEqual(0, poller1.attempt)
self.assertEqual(True, poller1.reachable)
# still alive, just unreach
self.assertEqual(False, poller2.alive)
self.assertEqual(3, poller2.attempt)
self.assertEqual(False, poller2.reachable)
# and others satellites too
self.assertEqual(True, reactionner1.alive)
self.assertEqual(0, reactionner1.attempt)
self.assertEqual(True, reactionner1.reachable)
# still alive, just unreach
self.assertEqual(False, reactionner2.alive)
self.assertEqual(3, reactionner2.attempt)
self.assertEqual(False, reactionner2.reachable)
# and others satellites too
self.assertEqual(True, broker1.alive)
self.assertEqual(0, broker1.attempt)
self.assertEqual(True, broker1.reachable)
# still alive, just unreach
self.assertEqual(True, broker2.alive)
self.assertEqual(0, broker2.attempt)
self.assertEqual(True, broker2.reachable)
# Now we check how we should dispatch confs
self.dispatcher.check_dispatch()
# the conf should not be in a good shape
self.assertEqual(False, self.dispatcher.dispatch_ok)
# Now we really dispatch them!
self.dispatcher.dispatch()
self.assert_any_log_match('Dispatch OK of conf in scheduler scheduler-all-1')
self.assert_any_log_match('Dispatch OK of configuration 0 to reactionner reactionner-all-1')
self.assert_any_log_match('Dispatch OK of configuration 0 to poller poller-all-1')
self.assert_any_log_match('Dispatch OK of configuration 0 to broker broker-all-1')
self.assert_any_log_match('Dispatch OK of configuration 1 to broker broker-all-2')
self.clear_logs()
# And look if we really dispatch conf as we should
for r in self.conf.realms:
for cfg in r.confs.values():
self.assertEqual(True, cfg.is_assigned)
self.assertIn(cfg.assigned_to, [scheduler1, scheduler2])
if __name__ == '__main__':
unittest.main()
| 18,925
|
Python
|
.py
| 423
| 36.241135
| 103
| 0.67208
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,364
|
test_db_mysql.py
|
shinken-solutions_shinken/test/test_db_mysql.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
try:
from shinken.db_mysql import DBMysql
except ImportError:
# Oups this server do not have mysql installed, skip this test
DBMysql = None
class TestConfig(ShinkenTest):
# setUp is inherited from ShinkenTest
def create_db(self):
self.db = DBMysql(host='localhost', user='root', password='root', database='merlin', character_set='utf8')
def test_connect_database(self):
if not DBMysql:
return
self.create_db()
try:
self.db.connect_database()
except Exception: # arg, no database here? sic!
pass
def test_execute_query(self):
if not DBMysql:
return
self.create_db()
try:
self.db.connect_database()
q = "DELETE FROM service WHERE instance_id = '0'"
self.db.execute_query(q)
except Exception:
pass
if __name__ == '__main__':
unittest.main()
| 1,940
|
Python
|
.py
| 53
| 31.622642
| 114
| 0.691898
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,365
|
test_nat.py.skip
|
shinken-solutions_shinken/test/test_nat.py.skip
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Guillaume Bour/Uperto, guillaume.bour@uperto.com
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file test Shinken working in a NATted environment
# Makes use of netkit (www.netkit.org) software
#
import os
import sys
import time
import glob
import shutil
import os.path
import unittest
import subprocess
SVC_CMD = "cd /hostlab && ./bin/shinken-#svc# -d -r -c ./test/etc/netkit/basic/#svc#d.ini\n"
launchers = {
'arbiter': "cd /hostlab/var && ../bin/shinken-#svc# -r -c ../etc/shinken.cfg -c ../test/etc/netkit/#conf#/shinken-specific.cfg 2>&1 > ./arbiter.debug&\n",
'broker': SVC_CMD,
'poller': SVC_CMD,
'reactionner': SVC_CMD,
'receiver': SVC_CMD,
'scheduler': SVC_CMD,
}
LOGBASE = os.path.join("#root#", "var")
LOGFILE = os.path.join(LOGBASE, "#svc#d.log")
logs = {
'arbiter': os.path.join(LOGBASE, "arbiter.debug"),
'broker': LOGFILE,
'poller': LOGFILE,
'reactionner': LOGFILE,
'receiver': LOGFILE,
'scheduler': LOGFILE,
}
def cleanup():
rootdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), "..")
subprocess.Popen(["lcrash", "--keep-fs", "-d", rootdir], stdout=open('/dev/null'), stderr=subprocess.STDOUT)
for prefix in ('pc1', 'pc2', 'nat'):
for f in glob.glob(os.path.join(rootdir, prefix + '.*')):
os.remove(f)
class TestNat(ShinkenTest):
def setUp(self):
self.testdir = os.path.dirname(os.path.abspath(sys.argv[0]))
self.files = dict()
# copying netkit configuration file to project root directory
root = os.path.join(self.testdir, 'etc', 'netkit')
for f in os.listdir(root):
if os.path.isfile(os.path.join(root, f)):
shutil.copy(os.path.join(root, f), os.path.join(self.testdir, '..'))
self.files[f] = os.path.join(self.testdir, '..', f)
for vm in ('pc1', 'pc2', 'nat'):
lock = os.path.join(self.testdir, '..', vm+'.STARTED')
if os.path.exists(lock):
os.remove(lock)
self.files[vm+'.lock'] = lock
# cleanup shinken logs
for f in glob.glob(os.path.join(self.testdir, "..", "var", "*.log")):
os.remove(f)
try:
os.remove(logs['arbiter'].replace('#root#', os.path.join(self.testdir, "..")))
except:
pass
def tearDown(self):
null = open('/dev/null')
subprocess.Popen(["lhalt", "-q", "-d", os.path.join(self.testdir, "..")], stdout=null, stderr=subprocess.STDOUT)
time.sleep(20)
subprocess.Popen(["lcrash", "--keep-fs", "-d", os.path.join(self.testdir, "..")], stdout=null, stderr=subprocess.STDOUT)
time.sleep(60)
for k, f in self.files.iteritems(): # glob.glob(os.path.join(self.testdir, "..", "*.STARTED"));
if os.path.exists(f):
os.remove(f)
def booted(self):
if not os.path.exists(os.path.join(self.testdir, "..", "pc1.STARTED")):
return False
return os.path.exists(os.path.join(self.testdir, "..", "pc2.STARTED"))
def init_and_start_vms(self, conf, services):
for vm in ('pc1', 'pc2', 'nat'):
f = open(self.files[vm+'.startup'], 'a')
# extend vm startup
extend = os.path.join(self.testdir, "etc", "netkit", conf, vm+".startup")
if os.path.exists(extend):
e = open(extend, 'r')
for l in e.xreadlines():
f.write(l)
e.close()
for svc in services.get(vm, []):
f.write(launchers[svc].replace('#svc#', svc).replace('#conf#', conf))
f.write("touch /hostlab/"+vm+".STARTED\n")
f.close()
subprocess.Popen(["lstart", "-d", os.path.join(self.testdir, ".."), "-f"], stdout=open('/dev/null'), stderr=subprocess.STDOUT)
# waiting for vms has finished booting
while not self.booted():
time.sleep(10)
print "init_and_start_vms %s done!" % conf
def found_in_log(self, svc, msg):
f = open(logs[svc].replace('#root#', os.path.join(self.testdir, "..")).replace('#svc#', svc), 'r')
for line in f.xreadlines():
if msg in line:
f.close()
return True
f.close()
return False
def test_01_failed_broker(self):
print "conf-01: init..."
self.init_and_start_vms('conf-01', {
'pc1': ['arbiter', 'poller', 'reactionner', 'receiver', 'scheduler'],
'pc2': ['broker']
})
# waiting 5mins to be sure arbiter sent its configuration to other services
print "waiting..."
time.sleep(60)
print "checking..."
self.assertTrue(self.found_in_log('broker', 'Info: Waiting for initial configuration'))
self.assertTrue(self.found_in_log('arbiter', 'Warning: Missing satellite broker for configuration 0:'))
self.assertFalse(self.found_in_log('arbiter', 'Info: [All] Dispatch OK of configuration 0 to broker broker-1'))
def test_02_broker(self):
print "conf-02: init..."
self.init_and_start_vms('conf-02', {
'pc1': ['arbiter', 'poller', 'reactionner', 'receiver', 'scheduler'],
'pc2': ['broker']
})
# waiting 3mins to be sure arbiter sent its configuration to other services
print "waiting..."
time.sleep(210)
print "checking..."
self.assertTrue(self.found_in_log('broker', 'Info: Waiting for initial configuration'))
self.assertTrue(self.found_in_log('arbiter', 'Info: [All] Dispatch OK of configuration 0 to broker broker-1'))
self.assertTrue(self.found_in_log('broker', 'Info: [broker-1] Connection OK to the scheduler scheduler-1'))
self.assertTrue(self.found_in_log('broker', 'Info: [broker-1] Connection OK to the poller poller-1'))
self.assertTrue(self.found_in_log('broker', 'Info: [broker-1] Connection OK to the reactionner reactionner-1'))
if __name__ == '__main__':
#import cProfile
command = """unittest.main()"""
unittest.main()
#cProfile.runctx( command, globals(), locals(), filename="/tmp/livestatus.profile" )
#allsuite = unittest.TestLoader.loadTestsFromModule(TestConfig)
#unittest.TextTestRunner(verbosity=2).run(allsuite)
cleanup()
| 7,142
|
Python
|
.py
| 156
| 38.288462
| 158
| 0.616271
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,366
|
test_servicedependency_explode_hostgroup.py
|
shinken-solutions_shinken/test/test_servicedependency_explode_hostgroup.py
|
#!/usr/bin/env python2.6
#Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
#This file is part of Shinken.
#
#Shinken is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Shinken 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 Affero General Public License for more details.
#
#You should have received a copy of the GNU Affero General Public License
#along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
#It's ugly I know....
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestServiceDepAndGroups(ShinkenTest):
#Uncomment this is you want to use a specific configuration
#for your test
def setUp(self):
self.setup_with_file('etc/shinken_servicedependency_explode_hostgroup.cfg')
#Change ME :)
def test_explodehostgroup(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
svc = self.sched.services.find_srv_by_name_and_hostname("test_router_0", "SNMP")
self.assertEqual(len(svc.act_depend_of_me), 2)
service_dependencies = []
service_dependency_postfix = self.sched.services.find_srv_by_name_and_hostname("test_router_0", "POSTFIX")
service_dependency_cpu = self.sched.services.find_srv_by_name_and_hostname("test_router_0", "CPU")
service_dependencies.append(service_dependency_postfix)
service_dependencies.append(service_dependency_cpu)
# Is service correctly depend of first one
all_services = []
for services in svc.act_depend_of_me:
all_services.extend(services)
self.assertIn(service_dependency_postfix, all_services)
self.assertIn(service_dependency_cpu, all_services)
if __name__ == '__main__':
unittest.main()
| 2,325
|
Python
|
.py
| 52
| 40.019231
| 114
| 0.7249
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,367
|
test_host_without_cmd.py
|
shinken-solutions_shinken/test/test_host_without_cmd.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_host_without_cmd.cfg')
def test_host_is_pending(self):
self.print_header()
# first of all, a host without check_command must be valid
self.assertTrue(self.conf.conf_is_correct)
# service always ok, host stays pending
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
for c in host.get_checks_in_progress():
# hurry up, we need an immediate result
c.t_to_go = 0
# scheduler.schedule() always schedules a check, even for this
# kind of hosts
#host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
host.checks_in_progress = []
host.in_checking = False
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
# this time we need the dependency from service to host
#svc.act_depend_of = [] # no hostchecks on critical checkresults
# initially the host is pending
self.assertEqual('PENDING', host.state)
self.assertEqual('PENDING', svc.state)
# now force a dependency check of the host
self.scheduler_loop(2, [[svc, 2, 'BAD | value1=0 value2=0']])
self.show_actions()
# and now the host is magically UP
self.assertEqual('UP', host.state)
self.assertEqual('HARD', host.state_type)
self.assertEqual('Host assumed to be UP', host.output)
if __name__ == '__main__':
unittest.main()
| 2,610
|
Python
|
.py
| 59
| 38.661017
| 91
| 0.683196
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,368
|
test_triggers.py
|
shinken-solutions_shinken/test/test_triggers.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
from shinken.objects.trigger import Trigger
class TestTriggers(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_triggers.cfg')
# Try to catch the perf_datas of self
def test_function_perf(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "sample_perf_function")
svc.output = 'I am OK'
svc.perf_data = 'cpu=95%'
# Go launch it!
svc.eval_triggers()
self.scheduler_loop(2, [])
print("Output", svc.output)
print("Perf_Data", svc.perf_data)
self.assertEqual("not good!", svc.output)
self.assertEqual("cpu=95%", svc.perf_data)
# Try to catch the perf_datas of self
def test_function_perfs(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "AVG-HTTP")
srvs = []
for i in range(1, 4):
s = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "HTTP-" + str(i))
s.output = 'Http ok'
s.perf_data = 'time=%dms' % i
# Go launch it!
svc.eval_triggers()
self.scheduler_loop(4, [])
print("Output", svc.output)
print("Perf_Data", svc.perf_data)
self.assertEqual("OK all is green", svc.output)
self.assertEqual("avgtime=2ms", svc.perf_data)
# Try to catch the perf_datas of self
def test_function_custom(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "sample_custom_function")
svc.output = 'Nb users?'
svc.perf_data = 'users=6'
# Go launch it!
svc.eval_triggers()
self.scheduler_loop(4, [])
print("Output", svc.output)
print("Perf_Data", svc.perf_data)
self.assertEqual("OK all is green", svc.output)
self.assertEqual("users=12", svc.perf_data)
def test_in_conf_trigger(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "i_got_trigger")
print('will run', svc.trigger)
# Go!
svc.eval_triggers()
print("Output", svc.output)
print("Perf_Data", svc.perf_data)
self.assertEqual("New output", svc.output)
self.assertEqual("New perf_data", svc.perf_data)
# Try to catch the perf_datas of self
def test_simple_cpu_too_high(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "cpu_too_high")
svc.output = 'I am OK'
svc.perf_data = 'cpu=95%'
# Go launch it!
svc.eval_triggers()
print("Output", svc.output)
print("Perf_Data", svc.perf_data)
self.assertEqual("not good!", svc.output)
self.assertEqual("cpu=95%", svc.perf_data)
# Same with a host
host = self.sched.hosts.find_by_name("test_host_trigger")
host.output = 'I am OK'
host.perf_data = 'cpu=95%'
# Go launch it!
host.eval_triggers()
self.scheduler_loop(2, [])
print("Output", host.output)
print("Perf_Data", host.perf_data)
self.assertEqual("not good!", host.output)
self.assertEqual("cpu=95", host.perf_data)
# Try to catch the perf_datas of self
def test_morecomplex_cpu_too_high(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "cpu_too_high_bis")
firstlen = len([b for b in self.sched.broks if b.type == 'service_check_result'])
self.scheduler_loop(1, [(svc, 0, 'I am OK | cpu=95%')])
seclen = len([b for b in self.sched.broks if b.type == 'service_check_result'])
self.scheduler_loop(1, [])
print("Output", svc.output)
print("Perf_Data", svc.perf_data)
print(firstlen, seclen)
self.assertEqual("not good!", svc.output)
self.assertEqual("cpu=95", svc.perf_data)
self.assertEqual(seclen, firstlen)
# Try to load .trig files
def test_trig_file_loading(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "cpu_too_high_ter")
t = self.conf.triggers.find_by_name('simple_cpu')
self.assertIn(t, svc.triggers)
svc.output = 'I am OK'
svc.perf_data = 'cpu=95%'
svc.eval_triggers()
self.scheduler_loop(2, [])
print("Output", svc.output)
print("Perf_Data", svc.perf_data)
self.assertEqual("not good!", svc.output)
self.assertEqual("cpu=95", svc.perf_data)
# same for host
host = self.sched.hosts.find_by_name('test_host_trigger2')
t = self.conf.triggers.find_by_name('simple_cpu')
self.assertIn(t, host.triggers)
host.output = 'I am OK'
host.perf_data = 'cpu=95%'
host.eval_triggers()
self.scheduler_loop(2, [])
print("Output", host.output)
print("Perf_Data", host.perf_data)
self.assertEqual("not good!", host.output)
self.assertEqual("cpu=95", host.perf_data)
def test_simple_triggers(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
code = '''r = self.get_name()'''.replace(r'\n', '\n').replace(r'\t', '\t')
t = Trigger({'trigger_name': 'none', 'code_src': code})
t.compile()
r = t.eval(svc)
print(r)
code = '''self.output = "Moncul c'est du poulet" '''.replace(r'\n', '\n').replace(r'\t', '\t')
t = Trigger({'trigger_name': 'none', 'code_src': code})
t.compile()
r = t.eval(svc)
print("Service output", svc.output)
self.assertEqual("Moncul c'est du poulet", svc.output)
code = '''self.output = "Moncul c'est du poulet2"
self.perf_data = "Moncul c'est du poulet3"
'''.replace(r'\n', '\n').replace(r'\t', '\t')
t = Trigger({'trigger_name': 'none', 'code_src': code})
t.compile()
r = t.eval(svc)
print("Service output", svc.output)
print("Service perf_data", svc.perf_data)
self.assertEqual("Moncul c'est du poulet2", svc.output)
self.assertEqual("Moncul c'est du poulet3", svc.perf_data)
if __name__ == '__main__':
unittest.main()
| 7,258
|
Python
|
.py
| 165
| 36.563636
| 104
| 0.623851
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,369
|
test_disable_active_checks.py
|
shinken-solutions_shinken/test/test_disable_active_checks.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestDisableActiveChecks(ShinkenTest):
# Uncomment this is you want to use a specific configuration
# for your test
#def setUp(self):
# self.setup_with_file('etc/shinken_disable_active_checks.cfg')
# We try to disable the actie checks and see if it's really done
# with a dummy check, so we need to get the same state and output
def test_disable_active_checks(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
print("Checks in progress", host.checks_in_progress)
c = host.get_checks_in_progress().pop()
print(c.__dict__)
print(c.status)
self.scheduler_loop(1, [[host, 0, 'I set this host UP | value1=1 value2=2']])
self.assertEqual('UP', host.state)
self.assertEqual('HARD', host.state_type)
last_output = host.output
host.schedule()
self.sched.external_command.DISABLE_HOST_CHECK(host)
c = host.get_checks_in_progress().pop()
print(c.__dict__)
print(c.status)
self.assertEqual('waitconsume', c.status)
self.scheduler_loop(2, [])
print(host.state)
print(host.output)
self.assertEqual(last_output, host.output)
print(len(host.get_checks_in_progress()))
print(host.is_in_checking())
self.assertEqual(False, host.is_in_checking())
if __name__ == '__main__':
unittest.main()
| 2,593
|
Python
|
.py
| 62
| 36.403226
| 85
| 0.686431
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,370
|
shinken_modules.py
|
shinken-solutions_shinken/test/shinken_modules.py
|
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import re
import copy
import time
import subprocess
import shutil
import datetime # not used but "sub-"imported by livestatus test.. (to be corrected..)
import sys # not here used but "sub-"imported by livestatus test.. (to be corrected..)
#
from shinken.modulesctx import modulesctx
from shinken.objects.module import Module
from shinken.modulesmanager import ModulesManager
from shinken.misc.datamanager import datamgr
from shinken.log import logger
#
from shinken_test import (
modules_dir,
ShinkenTest,
time_hacker, # not used here but "sub"-imported by lvestatus test (to be corrected)
)
modulesctx.set_modulesdir(modules_dir)
# Special Livestatus module opening since the module rename
#from shinken.modules.livestatus import module as livestatus_broker
livestatus_broker = modulesctx.get_module('livestatus')
LiveStatus_broker = livestatus_broker.LiveStatus_broker
LiveStatus = livestatus_broker.LiveStatus
LiveStatusRegenerator = livestatus_broker.LiveStatusRegenerator
LiveStatusQueryCache = livestatus_broker.LiveStatusQueryCache
LiveStatusClientThread = livestatus_broker.LiveStatusClientThread
Logline = livestatus_broker.Logline
LiveStatusLogStoreMongoDB = modulesctx.get_module('logstore-mongodb').LiveStatusLogStoreMongoDB
LiveStatusLogStoreSqlite = modulesctx.get_module('logstore-sqlite').LiveStatusLogStoreSqlite
livestatus_modconf = Module()
livestatus_modconf.module_name = "livestatus"
livestatus_modconf.module_type = livestatus_broker.properties['type']
livestatus_modconf.properties = livestatus_broker.properties.copy()
class ShinkenModulesTest(ShinkenTest):
def do_load_modules(self):
self.modules_manager.load_and_init()
self.log.log("I correctly loaded the modules: [%s]" % (','.join([inst.get_name() for inst in self.modules_manager.instances])))
def update_broker(self, dodeepcopy=False):
# The brok should be manage in the good order
ids = self.sched.brokers['Default-Broker']['broks'].keys()
ids.sort()
for brok_id in ids:
brok = self.sched.brokers['Default-Broker']['broks'][brok_id]
#print("Managing a brok type", brok.type, "of id", brok_id)
#if brok.type == 'update_service_status':
# print("Problem?", brok.data['is_problem'])
if dodeepcopy:
brok = copy.deepcopy(brok)
brok.prepare()
self.livestatus_broker.manage_brok(brok)
self.sched.brokers['Default-Broker']['broks'] = {}
def init_livestatus(self, modconf=None, dbmodconf=None, needcache=False):
self.livelogs = 'tmp/livelogs.db' + self.testid
if modconf is None:
modconf = Module({'module_name': 'LiveStatus',
'module_type': 'livestatus',
'port': str(50000 + os.getpid()),
'pnp_path': 'tmp/pnp4nagios_test' + self.testid,
'host': '127.0.0.1',
'socket': 'live',
'name': 'test', #?
})
if dbmodconf is None:
dbmodconf = Module({'module_name': 'LogStore',
'module_type': 'logstore_sqlite',
'use_aggressive_sql': "0",
'database_file': self.livelogs,
'archive_path': os.path.join(os.path.dirname(self.livelogs), 'archives'),
})
modconf.modules = [dbmodconf]
self.livestatus_broker = LiveStatus_broker(modconf)
self.livestatus_broker.create_queues()
#--- livestatus_broker.main
self.livestatus_broker.log = logger
# this seems to damage the logger so that the scheduler can't use it
#self.livestatus_broker.log.load_obj(self.livestatus_broker)
self.livestatus_broker.debug_output = []
self.livestatus_broker.modules_manager = ModulesManager('livestatus', modules_dir, [])
self.livestatus_broker.modules_manager.set_modules(self.livestatus_broker.modules)
# We can now output some previouly silented debug ouput
self.livestatus_broker.do_load_modules()
for inst in self.livestatus_broker.modules_manager.instances:
if inst.properties["type"].startswith('logstore'):
f = getattr(inst, 'load', None)
if f and callable(f):
f(self.livestatus_broker) # !!! NOT self here !!!!
break
for s in self.livestatus_broker.debug_output:
print("errors during load", s)
del self.livestatus_broker.debug_output
self.livestatus_broker.rg = LiveStatusRegenerator()
self.livestatus_broker.datamgr = datamgr
datamgr.load(self.livestatus_broker.rg)
self.livestatus_broker.query_cache = LiveStatusQueryCache()
if not needcache:
self.livestatus_broker.query_cache.disable()
self.livestatus_broker.rg.register_cache(self.livestatus_broker.query_cache)
#--- livestatus_broker.main
self.livestatus_broker.init()
self.livestatus_broker.db = self.livestatus_broker.modules_manager.instances[0]
self.livestatus_broker.livestatus = LiveStatus(self.livestatus_broker.datamgr, self.livestatus_broker.query_cache, self.livestatus_broker.db, self.livestatus_broker.pnp_path, self.livestatus_broker.from_q)
#--- livestatus_broker.do_main
self.livestatus_broker.db.open()
if hasattr(self.livestatus_broker.db, 'prepare_log_db_table'):
self.livestatus_broker.db.prepare_log_db_table()
#--- livestatus_broker.do_main
class TestConfig(ShinkenModulesTest):
def tearDown(self):
self.livestatus_broker.db.close()
if os.path.exists(self.livelogs):
os.remove(self.livelogs)
if os.path.exists(self.livelogs + "-journal"):
os.remove(self.livelogs + "-journal")
if os.path.exists(self.livestatus_broker.pnp_path):
shutil.rmtree(self.livestatus_broker.pnp_path)
if os.path.exists('var/shinken.log'):
os.remove('var/shinken.log')
if os.path.exists('var/retention.dat'):
os.remove('var/retention.dat')
if os.path.exists('var/status.dat'):
os.remove('var/status.dat')
self.livestatus_broker = None
def contains_line(self, text, pattern):
regex = re.compile(pattern)
for line in text.splitlines():
if re.search(regex, line):
return True
return False
def update_broker(self, dodeepcopy=False):
# The brok should be manage in the good order
ids = self.sched.brokers['Default-Broker']['broks'].keys()
ids.sort()
for brok_id in ids:
brok = self.sched.brokers['Default-Broker']['broks'][brok_id]
#print("Managing a brok type", brok.type, "of id", brok_id)
#if brok.type == 'update_service_status':
# print("Problem?", brok.data['is_problem'])
if dodeepcopy:
brok = copy.deepcopy(brok)
brok.prepare()
self.livestatus_broker.manage_brok(brok)
self.sched.brokers['Default-Broker']['broks'] = {}
def lines_equal(self, text1, text2):
# gets two multiline strings and compares the contents
# lifestatus output may not be in alphabetical order, so this
# function is used to compare unordered output with unordered
# expected output
# sometimes mklivestatus returns 0 or 1 on an empty result
text1 = text1.replace("200 1", "200 0")
text2 = text2.replace("200 1", "200 0")
text1 = text1.rstrip()
text2 = text2.rstrip()
#print("text1 //%s//" % text1)
#print("text2 //%s//" % text2)
sorted1 = "\n".join(sorted(text1.split("\n")))
sorted2 = "\n".join(sorted(text2.split("\n")))
len1 = len(text1.split("\n"))
len2 = len(text2.split("\n"))
#print("%s == %s text cmp %s" % (len1, len2, sorted1 == sorted2))
#print("text1 //%s//" % sorted(text1.split("\n")))
#print("text2 //%s//" % sorted(text2.split("\n")))
if sorted1 == sorted2 and len1 == len2:
return True
else:
# Maybe list members are different
# allhosts;test_host_0;test_ok_0;servicegroup_02,servicegroup_01,ok
# allhosts;test_host_0;test_ok_0;servicegroup_02,ok,servicegroup_01
# break it up to
# [['allhosts'], ['test_host_0'], ['test_ok_0'],
# ['ok', 'servicegroup_01', 'servicegroup_02']]
[line for line in sorted(text1.split("\n"))]
data1 = [[sorted(c.split(',')) for c in columns] for columns in [line.split(';') for line in sorted(text1.split("\n")) if line]]
data2 = [[sorted(c.split(',')) for c in columns] for columns in [line.split(';') for line in sorted(text2.split("\n")) if line]]
#print("text1 //%s//" % data1)
#print("text2 //%s//" % data2)
# cmp is clever enough to handle nested arrays
return cmp(data1, data2) == 0
def show_broks(self, title):
print
print("--- ", title)
for brok in sorted(self.sched.broks, lambda x, y: x.id - y.id):
if re.compile('^service_').match(brok.type):
pass
#print("BROK:", brok.type)
#print("BROK ", brok.data['in_checking'])
self.update_broker()
request = 'GET services\nColumns: service_description is_executing\n'
response, keepalive = self.livestatus_broker.livestatus.handle_request(request)
print(response)
| 9,784
|
Python
|
.py
| 194
| 41.273196
| 213
| 0.638979
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,371
|
test_missing_imported_from_module_property.py
|
shinken-solutions_shinken/test/test_missing_imported_from_module_property.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import time
from shinken_test import (
ShinkenTest, time_hacker, unittest
)
from shinken.modulesmanager import ModulesManager
from shinken.objects.module import Module
from shinken.log import logger
modules_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'module_missing_imported_from_module_property')
class TestMissingimportedFrom(ShinkenTest):
def setUp(self):
#logger.setLevel('DEBUG')
self.setup_with_file('etc/shinken_missing_imported_from_module_property.cfg')
# we are loading a module (dummy_arbiter) that is givving objects WITHOUT
# setting imported_from. One host got a warning, and this can crash without the imported_from setting
# in the arbiterdaemon part.
def test_missing_imported_from(self):
self.assertTrue(self.sched.conf.is_correct)
if __name__ == '__main__':
unittest.main()
| 1,851
|
Python
|
.py
| 43
| 40.534884
| 118
| 0.76546
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,372
|
test_no_broker_in_realm_warning.py
|
shinken-solutions_shinken/test/test_no_broker_in_realm_warning.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestWarnAboutNoBrokerInRealm(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_no_broker_in_realm_warning.cfg')
def test_no_broker_in_realm_warning(self):
dist = self.conf.realms.find_by_name("Distant")
self.assertIsNot(dist, None)
sched = self.conf.schedulers.find_by_name("Scheduler-distant")
self.assertIsNot(sched, None)
self.assertEqual(0, len(sched.realm.potential_brokers))
if __name__ == '__main__':
unittest.main()
| 1,504
|
Python
|
.py
| 35
| 40
| 82
| 0.745205
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,373
|
test_hostgroup_with_space.py
|
shinken-solutions_shinken/test/test_hostgroup_with_space.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestHostGroupWithSpace(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_hostgroup_with_space.cfg')
def test_hostgroup_with_space(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_With Spaces")
self.assertIsNot(svc, None)
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", 'test_With anoter Spaces')
self.assertIsNot(svc, None)
if __name__ == '__main__':
unittest.main()
| 1,498
|
Python
|
.py
| 34
| 41.235294
| 105
| 0.744154
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,374
|
test_service_with_print_as_name.py
|
shinken-solutions_shinken/test/test_service_with_print_as_name.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestServiceWithPrintName(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_service_with_print_as_name.cfg')
def test_service_with_print_as_name(self):
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "print")
self.assertIsNot(svc, None)
if __name__ == '__main__':
unittest.main()
| 1,357
|
Python
|
.py
| 32
| 40.03125
| 87
| 0.75019
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,375
|
test_module_autogeneration.py
|
shinken-solutions_shinken/test/test_module_autogeneration.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestModuleAutogeneration(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_module_autogeneration.cfg')
def test_module_autogeneration(self):
arbiterlink = self.conf.arbiters.find_by_name('Default-Arbiter')
modules = [m.module_name for m in arbiterlink.modules]
self.assertListEqual(modules, ["NamedPipe-Autogenerated"])
if __name__ == '__main__':
unittest.main()
| 1,428
|
Python
|
.py
| 33
| 40.636364
| 82
| 0.754513
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,376
|
test_critmodulation.py
|
shinken-solutions_shinken/test/test_critmodulation.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestCritMod(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_critmodulation.cfg')
def test_critmodulation_def(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get our criticity modulation")
cm = self.sched.conf.businessimpactmodulations.find_by_name('CritMod')
self.assertIsNot(cm, None)
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
print(svc.business_impact_modulations)
self.assertIn(cm, svc.business_impact_modulations)
if __name__ == '__main__':
unittest.main()
| 1,679
|
Python
|
.py
| 40
| 38.225
| 91
| 0.729896
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,377
|
test_priority.py
|
shinken-solutions_shinken/test/test_priority.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestPollerTagGetchecks(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_priority.cfg')
def test_host_check_priority(self):
test_host_0 = self.sched.hosts.find_by_name("test_host_0")
test_host_1 = self.sched.hosts.find_by_name("test_host_1")
test_host_2 = self.sched.hosts.find_by_name("test_host_2")
self.assertEqual(test_host_0.priority, 100)
self.assertEqual(test_host_1.priority, 100)
self.assertEqual(test_host_2.priority, 50)
self.assertEqual(test_host_0.check_command.priority, 100)
self.assertEqual(test_host_1.check_command.priority, 10)
self.assertEqual(test_host_2.check_command.priority, 50)
def test_service_check_priority(self):
test_svc_00 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_0", "standard_service")
test_svc_01 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_0", "hi_prio_service")
test_svc_02 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_0", "med_prio_service")
self.assertEqual(test_svc_00.priority, 100)
self.assertEqual(test_svc_01.priority, 100)
self.assertEqual(test_svc_02.priority, 40)
self.assertEqual(test_svc_00.check_command.priority, 100)
self.assertEqual(test_svc_01.check_command.priority, 10)
self.assertEqual(test_svc_02.check_command.priority, 40)
test_svc_10 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_1", "standard_service")
test_svc_11 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_1", "hi_prio_service")
test_svc_12 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_1", "med_prio_service")
self.assertEqual(test_svc_10.priority, 100)
self.assertEqual(test_svc_11.priority, 100)
self.assertEqual(test_svc_12.priority, 40)
self.assertEqual(test_svc_10.check_command.priority, 100)
self.assertEqual(test_svc_11.check_command.priority, 10)
self.assertEqual(test_svc_12.check_command.priority, 40)
test_svc_20 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_2", "standard_service")
test_svc_21 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_2", "hi_prio_service")
test_svc_22 = self.sched.services.find_srv_by_name_and_hostname(
"test_host_2", "med_prio_service")
self.assertEqual(test_svc_20.priority, 50)
self.assertEqual(test_svc_21.priority, 50)
self.assertEqual(test_svc_22.priority, 40)
self.assertEqual(test_svc_20.check_command.priority, 50)
self.assertEqual(test_svc_21.check_command.priority, 50)
self.assertEqual(test_svc_22.check_command.priority, 40)
if __name__ == '__main__':
unittest.main()
| 3,935
|
Python
|
.py
| 76
| 45.052632
| 82
| 0.694589
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,378
|
test_multi_attribute.py
|
shinken-solutions_shinken/test/test_multi_attribute.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test multi valued attribute feature.
#
from __future__ import absolute_import, division, print_function, unicode_literals
import re
from shinken_test import unittest, ShinkenTest
class TestMultiVuledAttributes(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_multi_attribute.cfg')
def test_multi_valued_attributes(self):
hst1 = self.sched.hosts.find_by_name("test_host_01")
srv1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
self.assertIsNot(hst1, None)
self.assertIsNot(srv1, None)
# inherited parameter
self.assertIs(True, hst1.active_checks_enabled)
self.assertIs(True, srv1.active_checks_enabled)
# non list parameter (only the last value set should remain)
self.assertEqual(3, hst1.max_check_attempts)
self.assertEqual(3, srv1.max_check_attempts)
# list parameter (all items should appear in the order they are defined)
self.assertEqual(
sorted(['d', 'u', 'f', '1', 's', 'r']),
sorted(list(set(hst1.notification_options)))
)
self.assertEqual(
sorted(['c', 'u', 'f', '1', 's', 'r', 'w']),
sorted(list(set(srv1.notification_options)))
)
if __name__ == '__main__':
unittest.main()
| 2,164
|
Python
|
.py
| 50
| 38.26
| 88
| 0.695859
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,379
|
test_system_time_change.py
|
shinken-solutions_shinken/test/test_system_time_change.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestSystemTimeChange(ShinkenTest):
# setUp is inherited from ShinkenTest
def test_system_time_change(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
host = self.sched.hosts.find_by_name("test_host_0")
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
now = time.time()
now_str = time.asctime(time.localtime(now))
print("Now:", now)
print("Now:", time.asctime(time.localtime(now)))
tomorow = time.asctime(time.localtime(now + 86400))
yesterday = time.asctime(time.localtime(now - 86400))
# Simulate a change now, because by default the value is 1970
host.last_state_change = now
host.schedule()
host_check = host.actions[0]
svc.schedule()
srv_check = svc.actions[0]
print("Service check", srv_check, time.asctime(time.localtime(srv_check.t_to_go)))
print("Current Host last_state_change", time.asctime(time.localtime(host.last_state_change)))
# Ok, start to check for bad time
last_state_change = host.last_state_change
host.compensate_system_time_change(86400)
self.assertEqual(86400, host.last_state_change - last_state_change )
svc.compensate_system_time_change(86400)
print("Tomorow Host last_state_change", time.asctime(time.localtime(host.last_state_change)))
# And now a huge change: yesterday (so a 2 day move)
last_state_change = host.last_state_change
host.compensate_system_time_change(-86400 * 2)
self.assertEqual(-86400*2, host.last_state_change - last_state_change )
svc.compensate_system_time_change(-86400*2)
print("Yesterday Host last_state_change", time.asctime(time.localtime(host.last_state_change)))
# Ok, now the scheduler and check things
# Put checks in the scheduler
self.sched.get_new_actions()
host_to_go = host_check.t_to_go
srv_to_go = srv_check.t_to_go
print("current Host check", time.asctime(time.localtime(host_check.t_to_go)))
print("current Service check", time.asctime(time.localtime(srv_check.t_to_go)))
self.sched.sched_daemon.compensate_system_time_change(86400)
print("Tomorow Host check", time.asctime(time.localtime(host_check.t_to_go)))
print("Tomorow Service check", time.asctime(time.localtime(srv_check.t_to_go)))
self.assertEqual(86400, host_check.t_to_go - host_to_go )
self.assertEqual(86400, srv_check.t_to_go - srv_to_go )
# and yesterday
host_to_go = host_check.t_to_go
srv_to_go = srv_check.t_to_go
self.sched.sched_daemon.compensate_system_time_change(-86400*2)
print("Yesterday Host check", time.asctime(time.localtime(host_check.t_to_go)))
print("Yesterday Service check", time.asctime(time.localtime(srv_check.t_to_go)))
print("New host check", time.asctime(time.localtime(host.next_chk)))
self.assertEqual(host_check.t_to_go, host.next_chk)
self.assertEqual(srv_check.t_to_go, svc.next_chk)
self.assertEqual(-86400*2, host_check.t_to_go - host_to_go )
self.assertEqual(-86400*2, srv_check.t_to_go - srv_to_go )
if __name__ == '__main__':
unittest.main()
| 4,400
|
Python
|
.py
| 85
| 45.152941
| 103
| 0.687529
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,380
|
test_config.py
|
shinken-solutions_shinken/test/test_config.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_broken_1.cfg')
def test_conf_is_correct(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
self.assertFalse(self.conf.conf_is_correct)
#self.show_logs()
if __name__ == '__main__':
unittest.main()
| 1,387
|
Python
|
.py
| 36
| 35.416667
| 82
| 0.731199
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,381
|
test_bad_realm_conf.py
|
shinken-solutions_shinken/test/test_bad_realm_conf.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestBadRealmConf(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_bad_realm_conf.cfg')
def test_bad_conf(self):
self.assertFalse(self.conf.conf_is_correct)
self.assert_any_log_match(" Error : More than one realm are set to the default realm")
self.assert_any_log_match("\[host::.*\] the host .* got an invalid realm")
if __name__ == '__main__':
unittest.main()
| 1,426
|
Python
|
.py
| 33
| 40.606061
| 94
| 0.740607
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,382
|
test_business_correlator_notifications.py
|
shinken-solutions_shinken/test/test_business_correlator_notifications.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test business rules smart notifications behaviour.
#
from __future__ import absolute_import, division, print_function, unicode_literals
import time
from shinken_test import unittest, ShinkenTest, time_hacker
class TestBusinesscorrelNotifications(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_business_correlator_notifications.cfg')
def test_bprule_standard_notifications(self):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", "bp_rule_default")
svc_cor.act_depend_of = []
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
self.assertIs(False, svc_cor.business_rule_smart_notifications)
dummy = self.sched.hosts.find_by_name("dummy")
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv2")
self.scheduler_loop(2, [
[dummy, 0, 'UP dummy'],
[svc1, 0, 'OK test_host_01/srv1'],
[svc2, 2, 'CRITICAL test_host_02/srv2']], do_sleep=True)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_SVC_PROBLEM;test_host_02;srv2;2;1;1;lausser;blablub" % (now)
self.sched.run_external_command(cmd)
self.assertIs(True, svc2.problem_has_been_acknowledged)
self.scheduler_loop(1, [[svc_cor, None, None]], do_sleep=True)
self.scheduler_loop(1, [[svc_cor, None, None]])
self.assertEqual(2, svc_cor.business_rule.get_state())
self.assertIs(False, svc_cor.notification_is_blocked_by_item('PROBLEM'))
def test_bprule_smart_notifications_ack(self):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", "bp_rule_smart_notif")
svc_cor.act_depend_of = []
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
self.assertIs(True, svc_cor.business_rule_smart_notifications)
dummy = self.sched.hosts.find_by_name("dummy")
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv2")
self.scheduler_loop(2, [
[dummy, 0, 'UP dummy'],
[svc1, 0, 'OK test_host_01/srv1'],
[svc2, 2, 'CRITICAL test_host_02/srv2']], do_sleep=True)
self.assertEqual(2, svc_cor.business_rule.get_state())
self.assertIs(False, svc_cor.notification_is_blocked_by_item('PROBLEM'))
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_SVC_PROBLEM;test_host_02;srv2;2;1;1;lausser;blablub" % (now)
self.sched.run_external_command(cmd)
self.assertIs(True, svc2.problem_has_been_acknowledged)
self.scheduler_loop(1, [[svc_cor, None, None]], do_sleep=True)
self.scheduler_loop(1, [[svc_cor, None, None]])
self.assertIs(True, svc_cor.notification_is_blocked_by_item('PROBLEM'))
def test_bprule_smart_notifications_svc_ack_downtime(self):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", "bp_rule_smart_notif")
svc_cor.act_depend_of = []
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
self.assertIs(True, svc_cor.business_rule_smart_notifications)
self.assertIs(False, svc_cor.business_rule_downtime_as_ack)
dummy = self.sched.hosts.find_by_name("dummy")
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv2")
self.scheduler_loop(2, [
[dummy, 0, 'UP dummy'],
[svc1, 0, 'OK test_host_01/srv1'],
[svc2, 2, 'CRITICAL test_host_02/srv2']], do_sleep=True)
self.assertEqual(2, svc_cor.business_rule.get_state())
self.assertIs(False, svc_cor.notification_is_blocked_by_item('PROBLEM'))
duration = 600
now = time.time()
# fixed downtime valid for the next 10 minutes
cmd = "[%lu] SCHEDULE_SVC_DOWNTIME;test_host_02;srv2;%d;%d;1;0;%d;lausser;blablub" % (now, now, now + duration, duration)
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [[svc_cor, None, None]], do_sleep=True)
self.scheduler_loop(1, [[svc_cor, None, None]])
self.assertGreater(svc2.scheduled_downtime_depth, 0)
self.assertIs(False, svc_cor.notification_is_blocked_by_item('PROBLEM'))
svc_cor.business_rule_downtime_as_ack = True
self.scheduler_loop(1, [[svc_cor, None, None]], do_sleep=True)
self.scheduler_loop(1, [[svc_cor, None, None]])
self.assertIs(True, svc_cor.notification_is_blocked_by_item('PROBLEM'))
def test_bprule_smart_notifications_hst_ack_downtime(self):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", "bp_rule_smart_notif")
svc_cor.act_depend_of = []
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
self.assertIs(True, svc_cor.business_rule_smart_notifications)
self.assertIs(False, svc_cor.business_rule_downtime_as_ack)
dummy = self.sched.hosts.find_by_name("dummy")
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
svc2 = self.sched.services.find_srv_by_name_and_hostname("test_host_02", "srv2")
hst2 = self.sched.hosts.find_by_name("test_host_02")
self.scheduler_loop(2, [
[dummy, 0, 'UP dummy'],
[svc1, 0, 'OK test_host_01/srv1'],
[svc2, 2, 'CRITICAL test_host_02/srv2']], do_sleep=True)
self.assertEqual(2, svc_cor.business_rule.get_state())
self.assertIs(False, svc_cor.notification_is_blocked_by_item('PROBLEM'))
duration = 600
now = time.time()
# fixed downtime valid for the next 10 minutes
cmd = "[%lu] SCHEDULE_HOST_DOWNTIME;test_host_02;%d;%d;1;0;%d;lausser;blablub" % (now, now, now + duration, duration)
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [[svc_cor, None, None]], do_sleep=True)
self.scheduler_loop(1, [[svc_cor, None, None]])
self.assertGreater(hst2.scheduled_downtime_depth, 0)
self.assertIs(False, svc_cor.notification_is_blocked_by_item('PROBLEM'))
svc_cor.business_rule_downtime_as_ack = True
self.scheduler_loop(1, [[svc_cor, None, None]], do_sleep=True)
self.scheduler_loop(1, [[svc_cor, None, None]])
self.assertIs(True, svc_cor.notification_is_blocked_by_item('PROBLEM'))
def test_bprule_child_notification_options(self):
svc_cor = self.sched.services.find_srv_by_name_and_hostname("dummy", "bp_rule_child_notif")
svc_cor.act_depend_of = []
self.assertIs(True, svc_cor.got_business_rule)
self.assertIsNot(svc_cor.business_rule, None)
svc1 = self.sched.services.find_srv_by_name_and_hostname("test_host_01", "srv1")
hst2 = self.sched.hosts.find_by_name("test_host_02")
self.assertEqual(['w', 'u', 'c', 'r', 's'], svc1.notification_options)
self.assertEqual(['d', 'u', 'r', 's'], hst2.notification_options)
if __name__ == '__main__':
unittest.main()
| 8,223
|
Python
|
.py
| 141
| 50.404255
| 129
| 0.666252
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,383
|
test_acknowledge_with_expire.py
|
shinken-solutions_shinken/test/test_acknowledge_with_expire.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test acknowledge of problems
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
# Restore sleep functions
time_hacker.set_real_time()
class TestAcksWithExpire(ShinkenTest):
def test_ack_hard_service_with_expire(self):
self.print_header()
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#--------------------------------------------------------------
# initialize host/service state
#--------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']])
print("- 1 x OK -------------------------------------")
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(0, svc.current_notification_number)
#--------------------------------------------------------------
# first check the normal behavior
# service reaches hard;2
# at the end there must be 3 actions: eventhandler hard,
# master notification and contact notification
#--------------------------------------------------------------
print("- 2 x BAD get hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']])
self.assertEqual(1, svc.current_notification_number)
self.assertEqual(3, self.count_actions())
self.assert_log_match(5, 'SERVICE NOTIFICATION')
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# stay hard and wait for the second notification (notification_interval)
#--------------------------------------------------------------
print("- 2 x BAD stay hard -------------------------------------")
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=False)
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# admin wakes up and acknowledges the problem
# the ACK is the only log message
# a master notification is still around, but can't be sent
#--------------------------------------------------------------
self.assertFalse(svc.problem_has_been_acknowledged)
now = time.time()
cmd = "[%lu] ACKNOWLEDGE_SVC_PROBLEM_EXPIRE;test_host_0;test_ok_0;1;1;0;%d;lausser;blablub" % (now, int(now) + 5)
self.sched.run_external_command(cmd)
self.scheduler_loop(1, [], do_sleep=False)
self.assertTrue(svc.problem_has_been_acknowledged)
self.assert_log_match(1, 'ACKNOWLEDGEMENT \(CRITICAL\)')
self.scheduler_loop(2, [[svc, 2, 'BAD']], do_sleep=False)
self.assertEqual(1, self.count_logs())
self.assertEqual(1, self.count_actions())
self.show_and_clear_logs()
self.show_actions()
#--------------------------------------------------------------
# Wait 4 remove acknowledgement
# now notifications are sent again
#--------------------------------------------------------------
time.sleep(5)
# Wait a bit
self.sched.check_for_expire_acknowledge()
self.assertFalse(svc.problem_has_been_acknowledged)
#now = time.time()
#cmd = "[%lu] REMOVE_SVC_ACKNOWLEDGEMENT;test_host_0;test_ok_0" % now
#self.sched.run_external_command(cmd)
self.sched.get_new_actions()
self.worker_loop()
self.show_logs()
self.show_actions()
# the contact notification was sent immediately (t_to_go)
self.assertFalse(svc.problem_has_been_acknowledged)
self.show_logs()
self.show_actions()
if __name__ == '__main__':
unittest.main()
| 4,905
|
Python
|
.py
| 101
| 41.712871
| 121
| 0.551472
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,384
|
test_timeperiods_state_logs.py
|
shinken-solutions_shinken/test/test_timeperiods_state_logs.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestTPStateLog(ShinkenTest):
# Uncomment this is you want to use a specific configuration
# for your test
#def setUp(self):
# self.setup_with_file('etc/shinken_timeperiods_state_logs.cfg')
# A timeperiod state change should raise a log, and only when change.
def test_tp_state_log(self):
now = time.time()
tp = self.sched.timeperiods.find_by_name('24x7')
self.assertIsNot(tp, None)
tp.check_and_log_activation_change()
self.assert_any_log_match("TIMEPERIOD TRANSITION: 24x7;-1;1")
self.show_and_clear_logs()
# Now make this tp unable to be active again by removing al it's daterange:p
dr = tp.dateranges
tp.dateranges = []
tp.check_and_log_activation_change()
self.assert_any_log_match("TIMEPERIOD TRANSITION: 24x7;1;0")
self.show_and_clear_logs()
# Ok, let get back to work :)
tp.dateranges = dr
tp.check_and_log_activation_change()
self.assert_any_log_match("TIMEPERIOD TRANSITION: 24x7;0;1")
self.show_and_clear_logs()
if __name__ == '__main__':
unittest.main()
| 2,142
|
Python
|
.py
| 50
| 38.28
| 84
| 0.707892
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,385
|
test_orphaned.py
|
shinken-solutions_shinken/test/test_orphaned.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestOrphaned(ShinkenTest):
# Uncomment this is you want to use a specific configuration
# for your test
#def setUp(self):
# self.setup_with_file('etc/shinken_1r_1h_1s.cfg')
def test_orphaned(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
#self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [router, 0, 'UP | rtt=10'], [svc, 2, 'BAD | value1=0 value2=0']])
#self.assertEqual('UP', host.state)
#self.assertEqual('HARD', host.state_type)
svc.schedule()
print(svc.actions)
self.sched.get_new_actions()
for c in self.sched.checks.values():
print(c)
# simulate a orphaned situation
c.t_to_go = now - 301
c.status = 'inpoller'
self.sched.check_orphaned()
# Should be available to poller now :)
for c in self.sched.checks.values():
self.assertEqual('scheduled', c.status)
# And we correctly raise the log
self.assert_any_log_match('checks never came back for the satellite')
if __name__ == '__main__':
unittest.main()
| 2,770
|
Python
|
.py
| 64
| 37.390625
| 135
| 0.665058
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,386
|
test_notif_macros.py
|
shinken-solutions_shinken/test/test_notif_macros.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestNotifMacros(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_notif_macros.cfg')
def test_notif_macro(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
#now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [router, 0, 'UP | rtt=10'], [svc, 2, 'BAD | value1=0 value2=0']])
# Should got a notif here
self.assertGreater(len(svc.notifications_in_progress.values()), 0)
#n = svc.notifications_in_progress.values()[0]
got_notif = False
r = 'plugins/macros_check.sh "_HOSTADMINEMAIL=" "monemail@masociete.domain" ' \
'"_HOSTCOMPANYNAME=" "masociete" "_CONTACTTESTC=" "sender@masociete.domain" "toto"'
for a in self.sched.actions.values():
print(a.command)
if a.command == r:
got_notif = True
self.assertTrue(got_notif)
if __name__ == '__main__':
unittest.main()
| 2,579
|
Python
|
.py
| 57
| 39.578947
| 134
| 0.67078
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,387
|
test_multi_hostgroups_def.py
|
shinken-solutions_shinken/test/test_multi_hostgroups_def.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_multi_hostgroups_def.cfg')
def test_dummy(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("will crash")
self.assertIsNot(host, None)
svc = self.sched.services.find_srv_by_name_and_hostname("will crash", "Crash")
self.assertIsNot(svc, None)
grp = self.sched.servicegroups.find_by_name("Crashed")
self.assertIsNot(grp, None)
self.assertIn(svc, grp.members)
if __name__ == '__main__':
unittest.main()
| 1,740
|
Python
|
.py
| 43
| 36.372093
| 86
| 0.71327
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,388
|
test_missing_cariarereturn.py
|
shinken-solutions_shinken/test/test_missing_cariarereturn.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_missing_cariarereturn.cfg')
def test_dummy(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "TEST")
self.assertIsNot(svc, None)
self.assertGreaterEqual(len(svc.get_checks_in_progress()), 1)
print(svc.get_checks_in_progress()[0].command)
self.assertEqual('plugins/nothing BLABLA', svc.get_checks_in_progress()[0].command)
if __name__ == '__main__':
unittest.main()
| 1,723
|
Python
|
.py
| 41
| 38.170732
| 91
| 0.719665
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,389
|
test_properties.py
|
shinken-solutions_shinken/test/test_properties.py
|
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
"""
Test shinken.property
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import __import_shinken
import shinken
from shinken.property import none_object
from shinken_test import ShinkenTest, unittest
class PropertyTests:
"""Common tests for all property classes"""
def setUp(self):
pass
def test_no_default_value(self):
p = self.prop_class()
self.assertIs(p.default, none_object)
self.assertFalse(p.has_default)
self.assertTrue(p.required)
def test_default_value(self):
default_value = object()
p = self.prop_class(default=default_value)
self.assertIs(p.default, default_value)
self.assertTrue(p.has_default)
self.assertFalse(p.required)
def test_fill_brok(self):
p = self.prop_class()
self.assertNotIn('full_status', p.fill_brok)
p = self.prop_class(default='0', fill_brok=['full_status'])
self.assertIn('full_status', p.fill_brok)
def test_unused(self):
p = self.prop_class()
self.assertFalse(p.unused)
#ShinkenTest
class TestBoolProp(PropertyTests, ShinkenTest):
"""Test the BoolProp class"""
prop_class = shinken.property.BoolProp
def test_pythonize(self):
p = self.prop_class()
# allowed strings for `True`
self.assertEqual(p.pythonize("1"), True)
self.assertEqual(p.pythonize("yes"), True)
self.assertEqual(p.pythonize("true"), True)
self.assertEqual(p.pythonize("on"), True)
self.assertEqual(p.pythonize(["off", "on"]), True)
# allowed strings for `False`
self.assertEqual(p.pythonize("0"), False)
self.assertEqual(p.pythonize("no"), False)
self.assertEqual(p.pythonize("false"), False)
self.assertEqual(p.pythonize("off"), False)
self.assertEqual(p.pythonize(["on", "off"]), False)
class TestIntegerProp(PropertyTests, ShinkenTest):
"""Test the IntegerProp class"""
prop_class = shinken.property.IntegerProp
def test_pythonize(self):
p = self.prop_class()
self.assertEqual(p.pythonize("1"), 1)
self.assertEqual(p.pythonize("0"), 0)
self.assertEqual(p.pythonize("1000.33"), 1000)
self.assertEqual(p.pythonize(["2000.66", "1000.33"]), 1000)
class TestFloatProp(PropertyTests, ShinkenTest):
"""Test the FloatProp class"""
prop_class = shinken.property.FloatProp
def test_pythonize(self):
p = self.prop_class()
self.assertEqual(p.pythonize("1"), 1.0)
self.assertEqual(p.pythonize("0"), 0.0)
self.assertEqual(p.pythonize("1000.33"), 1000.33)
self.assertEqual(p.pythonize(["2000.66", "1000.33"]), 1000.33)
class TestStringProp(PropertyTests, ShinkenTest):
"""Test the StringProp class"""
prop_class = shinken.property.StringProp
def test_pythonize(self):
p = self.prop_class()
self.assertEqual(p.pythonize("1"), "1")
self.assertEqual(p.pythonize("yes"), "yes")
self.assertEqual(p.pythonize("0"), "0")
self.assertEqual(p.pythonize("no"), "no")
self.assertEqual(p.pythonize(["yes", "no"]), "no")
class TestCharProp(PropertyTests, ShinkenTest):
"""Test the CharProp class"""
prop_class = shinken.property.CharProp
def test_pythonize(self):
p = self.prop_class()
self.assertEqual(p.pythonize("c"), "c")
self.assertEqual(p.pythonize("cxxxx"), "c")
self.assertEqual(p.pythonize(["bxxxx", "cxxxx"]), "c")
# this raises IndexError. is this intented?
## self.assertEqual(p.pythonize(""), "")
class TestPathProp(TestStringProp):
"""Test the PathProp class"""
prop_class = shinken.property.PathProp
# As of now, PathProp is a subclass of StringProp without any
# relevant change. So no further tests are implemented here.
class TestConfigPathProp(TestStringProp):
"""Test the ConfigPathProp class"""
prop_class = shinken.property.ConfigPathProp
# As of now, ConfigPathProp is a subclass of StringProp without
# any relevant change. So no further tests are implemented here.
class TestListProp(PropertyTests, ShinkenTest):
"""Test the ListProp class"""
prop_class = shinken.property.ListProp
def test_pythonize(self):
p = self.prop_class()
self.assertEqual(p.pythonize(""), [])
self.assertEqual(p.pythonize("1,2,3"), ["1", "2", "3"])
# Default is to split on coma for list also.
self.assertEquals(p.pythonize(["1,2,3", "4,5,6"]), ["1","2","3", "4","5","6"])
def test_pythonize_nosplit(self):
p = self.prop_class(split_on_coma=False)
self.assertEqual(p.pythonize(""), [""])
self.assertEqual(p.pythonize("1,2,3"), ["1,2,3"])
# Default is to split on coma for list also.
self.assertEquals(p.pythonize(["1,2,3", "4,5,6"]), ["1,2,3", "4,5,6"])
class TestLogLevelProp(PropertyTests, ShinkenTest):
"""Test the LogLevelProp class"""
prop_class = shinken.property.LogLevelProp
def test_pythonize(self):
p = self.prop_class()
self.assertEqual(p.pythonize("NOTSET"), 0)
self.assertEqual(p.pythonize("DEBUG"), 10)
self.assertEqual(p.pythonize("INFO"), 20)
self.assertEqual(p.pythonize("WARN"), 30)
self.assertEqual(p.pythonize("WARNING"), 30)
self.assertEqual(p.pythonize("ERROR"), 40)
## 'FATAL' is not defined in std-module `logging._levelNames`
#self.assertEqual(p.pythonize("FATAL"), 50)
self.assertEqual(p.pythonize("CRITICAL"), 50)
self.assertEqual(p.pythonize(["NOTSET", "CRITICAL"]), 50)
## :todo: fix DictProp error if no `elts_prop` are passed
## class TestDictProp(PropertyTests, ShinkenTest):
## """Test the DictProp class"""
##
## prop_class = shinken.property.DictProp
##
## def test_pythonize(self):
## p = self.prop_class()
## self.assertEqual(p.pythonize(""), "")
class TestAddrProp(PropertyTests, ShinkenTest):
"""Test the AddrProp class"""
prop_class = shinken.property.AddrProp
def test_pythonize_with_IPv4_addr(self):
p = self.prop_class()
self.assertEqual(p.pythonize("192.168.10.11:445"),
{'address': "192.168.10.11",
'port': 445})
# no colon, no port
self.assertEqual(p.pythonize("192.168.10.11"),
{'address': "192.168.10.11"})
# colon but no port number
self.assertRaises(ValueError, p.pythonize, "192.168.10.11:")
# only colon, no addr, no port number
self.assertRaises(ValueError, p.pythonize, ":")
# no address, only port number
self.assertEqual(p.pythonize(":445"),
{'address': "",
'port': 445})
def test_pythonize_with_hostname(self):
p = self.prop_class()
self.assertEqual(p.pythonize("host_123:445"),
{'address': "host_123",
'port': 445})
# no colon, no port
self.assertEqual(p.pythonize("host_123"),
{'address': "host_123"})
# colon but no port number
self.assertRaises(ValueError, p.pythonize, "host_123:")
# only colon, no addr, no port number
self.assertRaises(ValueError, p.pythonize, ":")
# no address, only port number
self.assertEqual(p.pythonize(":445"),
{'address': "",
'port': 445})
self.assertEqual(p.pythonize([":444", ":445"]),
{'address': "",
'port': 445})
# :fixme: IPv6 addresses are no tested since they are not parsed
# correcly
if __name__ == '__main__':
unittest.main()
| 8,688
|
Python
|
.py
| 197
| 36.583756
| 86
| 0.638704
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,390
|
test_parse_logevent.py
|
shinken-solutions_shinken/test/test_parse_logevent.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2014 - Savoir-Faire Linux inc.
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
from shinken.misc.logevent import LogEvent
class TestParseLogEvent(ShinkenTest):
def test_notification_service(self):
log = '[1402515279] SERVICE NOTIFICATION: admin;localhost;check-ssh;CRITICAL;notify-service-by-email;Connection refused'
expected = {
'hostname': 'localhost',
'event_type': 'NOTIFICATION',
'service_desc': 'check-ssh',
'state': 'CRITICAL',
'contact': 'admin',
'time': 1402515279,
'notification_method': 'notify-service-by-email',
'notification_type': 'SERVICE',
'output': 'Connection refused',
}
event = LogEvent(log)
self.assertEqual(event.data, expected)
def test_notification_host(self):
log = '[1402515279] HOST NOTIFICATION: admin;localhost;CRITICAL;notify-service-by-email;Connection refused'
expected = {
'hostname': 'localhost',
'event_type': 'NOTIFICATION',
'service_desc': None,
'state': 'CRITICAL',
'contact': 'admin',
'time': 1402515279,
'notification_method': 'notify-service-by-email',
'notification_type': 'HOST',
'output': 'Connection refused',
}
event = LogEvent(log)
self.assertEqual(event.data, expected)
def test_alert_service(self):
log = '[1329144231] SERVICE ALERT: dfw01-is02-006;cpu load maui;WARNING;HARD;4;WARNING - load average: 5.04, 4.67, 5.04'
expected = {
'alert_type': 'SERVICE',
'event_type': 'ALERT',
'service_desc': 'cpu load maui',
'attempts': 4,
'state_type': 'HARD',
'state': 'WARNING',
'time': 1329144231,
'output': 'WARNING - load average: 5.04, 4.67, 5.04',
'hostname': 'dfw01-is02-006'
}
event = LogEvent(log)
self.assertEqual(event.data, expected)
def test_alert_host(self):
log = '[1329144231] HOST ALERT: dfw01-is02-006;WARNING;HARD;4;WARNING - load average: 5.04, 4.67, 5.04'
expected = {
'alert_type': 'HOST',
'event_type': 'ALERT',
'service_desc': None,
'attempts': 4,
'state_type': 'HARD',
'state': 'WARNING',
'time': 1329144231,
'output': 'WARNING - load average: 5.04, 4.67, 5.04',
'hostname': 'dfw01-is02-006'
}
event = LogEvent(log)
self.assertEqual(event.data, expected)
def test_downtime_alert_host(self):
log = '[1279250211] HOST DOWNTIME ALERT: maast64;STARTED; Host has entered a period of scheduled downtime'
expected = {
'event_type': 'DOWNTIME',
'hostname': 'maast64',
'state': 'STARTED',
'time': 1279250211,
'output': ' Host has entered a period of scheduled downtime',
'downtime_type': 'HOST'
}
event = LogEvent(log)
self.assertEqual(event.data, expected)
def test_host_flapping(self):
log = '[1375301662] SERVICE FLAPPING ALERT: testhost;check_ssh;STARTED; Service appears to have started flapping (24.2% change >= 20.0% threshold)'
expected = {
'alert_type': 'SERVICE',
'event_type': 'FLAPPING',
'hostname': 'testhost',
'output': ' Service appears to have started flapping (24.2% change >= 20.0% threshold)',
'service_desc': 'check_ssh',
'state': 'STARTED',
'time': 1375301662
}
event = LogEvent(log)
self.assertEqual(event.data, expected)
def test_service_flapping(self):
log = '[1375301662] HOST FLAPPING ALERT: hostbw;STARTED; Host appears to have started flapping (20.1% change > 20.0% threshold)'
expected = {
'alert_type': 'HOST',
'event_type': 'FLAPPING',
'hostname': 'hostbw',
'output': ' Host appears to have started flapping (20.1% change > 20.0% threshold)',
'service_desc': None,
'state': 'STARTED',
'time': 1375301662
}
event = LogEvent(log)
self.assertEqual(event.data, expected)
if __name__ == '__main__':
unittest.main()
| 5,193
|
Python
|
.py
| 122
| 33.385246
| 155
| 0.598378
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,391
|
test_create_link_from_ext_cmd.py
|
shinken-solutions_shinken/test/test_create_link_from_ext_cmd.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestCreateLinkFromExtCmd(ShinkenTest):
# Uncomment this is you want to use a specific configuration
# for your test
#def setUp(self):
# self.setup_with_file('etc/shinken_1r_1h_1s.cfg')
def test_simple_host_link(self):
now = int(time.time())
h = self.sched.hosts.find_by_name('test_host_0')
self.assertIsNot(h, None)
h.act_depend_of = []
r = self.sched.hosts.find_by_name('test_router_0')
self.assertIsNot(r, None)
r.act_depend_of = []
e = ExternalCommandManager(self.conf, 'dispatcher')
cmd = "[%lu] ADD_SIMPLE_HOST_DEPENDENCY;test_host_0;test_router_0" % now
self.sched.run_external_command(cmd)
self.assertTrue(h.is_linked_with_host(r))
# Now we remove this link
cmd = "[%lu] DEL_HOST_DEPENDENCY;test_host_0;test_router_0" % now
self.sched.run_external_command(cmd)
self.assertFalse(h.is_linked_with_host(r))
if __name__ == '__main__':
unittest.main()
| 2,007
|
Python
|
.py
| 47
| 38.425532
| 82
| 0.704103
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,392
|
test_uknown_event_handler.py
|
shinken-solutions_shinken/test/test_uknown_event_handler.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestUnknownEventHandler(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_uknown_event_handler.cfg')
def test_dummy(self):
self.assertFalse(self.conf.conf_is_correct)
if __name__ == '__main__':
unittest.main()
| 1,257
|
Python
|
.py
| 31
| 38.387097
| 82
| 0.756979
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,393
|
test_ocsp_command_and_poller_tag.py
|
shinken-solutions_shinken/test/test_ocsp_command_and_poller_tag.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestOCSPwithPollerTag(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_ocsp_command_and_poller_tag.cfg')
def test_ocsp_with_poller_tag(self):
host = self.sched.hosts.find_by_name("mysuperhost")
self.assertEqual(host.check_command.poller_tag, 'mytag')
self.assertEqual(host.check_command.command.poller_tag, 'Bla')
self.assertEqual(self.sched.conf.ocsp_command.command.poller_tag, 'Bla')
self.assertEqual(self.sched.conf.ocsp_command.poller_tag, 'Bla')
if __name__ == '__main__':
unittest.main()
| 1,577
|
Python
|
.py
| 35
| 42.057143
| 82
| 0.746736
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,394
|
test_command.py
|
shinken-solutions_shinken/test/test_command.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
from shinken.commandcall import CommandCall
from shinken.objects import Command, Commands
class TestCommand(ShinkenTest):
# setUp is inherited from ShinkenTest
def test_command(self):
t = {'command_name': 'check_command_test',
'command_line': '/tmp/dummy_command.sh $ARG1$ $ARG2$',
'poller_tag': 'DMZ'
}
c = Command(t)
self.assertEqual('check_command_test', c.command_name)
b = c.get_initial_status_brok()
self.assertEqual('initial_command_status', b.type)
# now create a commands packs
cs = Commands([c])
dummy_call = "check_command_test!titi!toto"
cc = CommandCall(cs, dummy_call)
self.assertEqual(True, cc.is_valid())
self.assertEqual(c, cc.command)
self.assertEqual('DMZ', cc.poller_tag)
if __name__ == '__main__':
unittest.main()
| 1,883
|
Python
|
.py
| 46
| 36.5
| 82
| 0.705367
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,395
|
test_not_execute_host_check.py
|
shinken-solutions_shinken/test/test_not_execute_host_check.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestNoHostCheck(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_not_execute_host_check.cfg')
# We must look taht host checks are disable, and services ones are running
def test_no_host_check(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
print(host.checks_in_progress)
self.assertEqual(0, len(host.get_checks_in_progress()))
#
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
print(svc.checks_in_progress)
self.assertNotEqual(len(svc.get_checks_in_progress()), 0)
# Now launch passive checks
cmd = "[%lu] PROCESS_HOST_CHECK_RESULT;test_host_0;1;bobo" % now
self.sched.run_external_command(cmd)
self.scheduler_loop(2, [])
print("Output", host.output)
self.assertEqual('bobo', host.output)
# Now disable passive host check
cmd = "[%lu] STOP_ACCEPTING_PASSIVE_HOST_CHECKS" % now
self.sched.run_external_command(cmd)
# And now run a new command
cmd = "[%lu] PROCESS_HOST_CHECK_RESULT;test_host_0;1;bobo2" % now
self.sched.run_external_command(cmd)
self.scheduler_loop(2, [])
# This should NOT change this time
print("Output", host.output)
self.assertEqual('bobo', host.output)
if __name__ == '__main__':
unittest.main()
| 2,590
|
Python
|
.py
| 60
| 37.616667
| 91
| 0.686828
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,396
|
test_serializer.py
|
shinken-solutions_shinken/test/test_serializer.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
import six
from shinken_test import *
from shinken.serializer import serialize, deserialize
import pickle
import sys
import io
class TestSerializer(ShinkenTest):
def setUp(self):
pass
def test_serializer(self):
ref = {"test": True}
payload = serialize(ref)
loaded = deserialize(payload)
self.assertEqual(ref, loaded)
if __name__ == '__main__':
unittest.main()
| 1,385
|
Python
|
.py
| 39
| 32.923077
| 82
| 0.749251
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,397
|
test_host_extented_info.py
|
shinken-solutions_shinken/test/test_host_extented_info.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_host_extented_info.cfg')
def test_dummy(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [router, 0, 'UP | rtt=10'], [svc, 2, 'BAD | value1=0 value2=0']])
self.assertEqual('UP', host.state)
self.assertEqual('HARD', host.state_type)
self.assertEqual('icon.png', host.icon_image)
if __name__ == '__main__':
unittest.main()
| 2,171
|
Python
|
.py
| 49
| 39.612245
| 134
| 0.685755
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,398
|
test_downtimes.py
|
shinken-solutions_shinken/test/test_downtimes.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test host- and service-downtimes.
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
#time.time = original_time_time
#time.sleep = original_time_sleep
class TestDowntime(ShinkenTest):
def test_schedule_fixed_svc_downtime(self):
self.print_header()
# schedule a 2-minute downtime
# downtime must be active
# consume a good result, sleep for a minute
# downtime must be active
# consume a bad result
# downtime must be active
# no notification must be found in broks
duration = 600
now = time.time()
# downtime valid for the next 2 minutes
cmd = "[%lu] SCHEDULE_SVC_DOWNTIME;test_host_0;test_ok_0;%d;%d;1;0;%d;lausser;blablub" % (now, now, now + duration, duration)
self.sched.run_external_command(cmd)
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
time.sleep(20)
self.scheduler_loop(1, [[svc, 0, 'OK']])
print("downtime was scheduled. check its activity and the comment")
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(svc.downtimes))
self.assertIn(svc.downtimes[0], self.sched.downtimes.values())
self.assertTrue(svc.downtimes[0].fixed)
self.assertTrue(svc.downtimes[0].is_in_effect)
self.assertFalse(svc.downtimes[0].can_be_deleted)
self.assertEqual(1, len(self.sched.comments))
self.assertEqual(1, len(svc.comments))
self.assertIn(svc.comments[0], self.sched.comments.values())
self.assertEqual(svc.comments[0].id, svc.downtimes[0].comment_id)
self.scheduler_loop(1, [[svc, 0, 'OK']])
print("good check was launched, downtime must be active")
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(svc.downtimes))
self.assertIn(svc.downtimes[0], self.sched.downtimes.values())
self.assertTrue(svc.in_scheduled_downtime)
self.assertTrue(svc.downtimes[0].fixed)
self.assertTrue(svc.downtimes[0].is_in_effect)
self.assertFalse(svc.downtimes[0].can_be_deleted)
self.scheduler_loop(1, [[svc, 2, 'BAD']])
print("bad check was launched (SOFT;1), downtime must be active")
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(svc.downtimes))
self.assertIn(svc.downtimes[0], self.sched.downtimes.values())
self.assertTrue(svc.in_scheduled_downtime)
self.assertTrue(svc.downtimes[0].fixed)
self.assertTrue(svc.downtimes[0].is_in_effect)
self.assertFalse(svc.downtimes[0].can_be_deleted)
# now the state changes to hard
self.scheduler_loop(1, [[svc, 2, 'BAD']])
print("bad check was launched (HARD;2), downtime must be active")
print(svc.downtimes[0])
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(svc.downtimes))
self.assertIn(svc.downtimes[0], self.sched.downtimes.values())
self.assertTrue(svc.in_scheduled_downtime)
self.assertTrue(svc.downtimes[0].fixed)
self.assertTrue(svc.downtimes[0].is_in_effect)
self.assertFalse(svc.downtimes[0].can_be_deleted)
scheduled_downtime_depth = svc.scheduled_downtime_depth
cmd = "[%lu] DEL_SVC_DOWNTIME;%d" % (now, svc.downtimes[0].id)
self.sched.run_external_command(cmd)
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(svc.downtimes))
self.assertFalse(svc.in_scheduled_downtime)
self.assertLess(svc.scheduled_downtime_depth, scheduled_downtime_depth)
self.assertTrue(svc.downtimes[0].fixed)
self.assertFalse(svc.downtimes[0].is_in_effect)
self.assertTrue(svc.downtimes[0].can_be_deleted)
self.assertEqual(1, len(self.sched.comments))
self.assertEqual(1, len(svc.comments))
# now a notification must be sent
self.scheduler_loop(1, [[svc, 2, 'BAD']])
# downtimes must have been deleted now
self.assertEqual(0, len(self.sched.downtimes))
self.assertEqual(0, len(svc.downtimes))
self.assertEqual(0, len(self.sched.comments))
self.assertEqual(0, len(svc.comments))
def test_schedule_flexible_svc_downtime(self):
self.print_header()
#----------------------------------------------------------------
# schedule a flexible downtime of 3 minutes for the host
#----------------------------------------------------------------
duration = 180
now = time.time()
cmd = "[%lu] SCHEDULE_SVC_DOWNTIME;test_host_0;test_ok_0;%d;%d;0;0;%d;lausser;blablub" % (now, now, now + duration, duration)
self.sched.run_external_command(cmd)
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
time.sleep(20)
#----------------------------------------------------------------
# check if a downtime object exists (scheduler and service)
# check if the downtime is still inactive
#----------------------------------------------------------------
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(svc.downtimes))
self.assertIn(svc.downtimes[0], self.sched.downtimes.values())
self.assertFalse(svc.downtimes[0].fixed)
self.assertFalse(svc.downtimes[0].is_in_effect)
self.assertFalse(svc.downtimes[0].can_be_deleted)
self.assertEqual(1, len(self.sched.comments))
self.assertEqual(1, len(svc.comments))
self.assertIn(svc.comments[0], self.sched.comments.values())
self.assertEqual(svc.comments[0].id, svc.downtimes[0].comment_id)
#----------------------------------------------------------------
# run the service and return an OK status
# check if the downtime is still inactive
#----------------------------------------------------------------
self.scheduler_loop(1, [[svc, 0, 'OK']])
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(svc.downtimes))
self.assertIn(svc.downtimes[0], self.sched.downtimes.values())
self.assertFalse(svc.in_scheduled_downtime)
self.assertFalse(svc.downtimes[0].fixed)
self.assertFalse(svc.downtimes[0].is_in_effect)
self.assertFalse(svc.downtimes[0].can_be_deleted)
time.sleep(61)
#----------------------------------------------------------------
# run the service twice to get a soft critical status
# check if the downtime is still inactive
#----------------------------------------------------------------
self.scheduler_loop(1, [[svc, 2, 'BAD']])
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(svc.downtimes))
self.assertIn(svc.downtimes[0], self.sched.downtimes.values())
self.assertFalse(svc.in_scheduled_downtime)
self.assertFalse(svc.downtimes[0].fixed)
self.assertFalse(svc.downtimes[0].is_in_effect)
self.assertFalse(svc.downtimes[0].can_be_deleted)
time.sleep(61)
#----------------------------------------------------------------
# run the service again to get a hard critical status
# check if the downtime is active now
#----------------------------------------------------------------
self.scheduler_loop(1, [[svc, 2, 'BAD']])
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(svc.downtimes))
self.assertIn(svc.downtimes[0], self.sched.downtimes.values())
self.assertTrue(svc.in_scheduled_downtime)
self.assertFalse(svc.downtimes[0].fixed)
self.assertTrue(svc.downtimes[0].is_in_effect)
self.assertFalse(svc.downtimes[0].can_be_deleted)
#----------------------------------------------------------------
# cancel the downtime
# check if the downtime is inactive now and can be deleted
#----------------------------------------------------------------
scheduled_downtime_depth = svc.scheduled_downtime_depth
cmd = "[%lu] DEL_SVC_DOWNTIME;%d" % (now, svc.downtimes[0].id)
self.sched.run_external_command(cmd)
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(svc.downtimes))
self.assertFalse(svc.in_scheduled_downtime)
self.assertLess(svc.scheduled_downtime_depth, scheduled_downtime_depth)
self.assertFalse(svc.downtimes[0].fixed)
self.assertFalse(svc.downtimes[0].is_in_effect)
self.assertTrue(svc.downtimes[0].can_be_deleted)
self.assertEqual(1, len(self.sched.comments))
self.assertEqual(1, len(svc.comments))
time.sleep(61)
#----------------------------------------------------------------
# run the service again with a critical status
# the downtime must have disappeared
# a notification must be sent
#----------------------------------------------------------------
self.scheduler_loop(1, [[svc, 2, 'BAD']])
self.assertEqual(0, len(self.sched.downtimes))
self.assertEqual(0, len(svc.downtimes))
self.assertEqual(0, len(self.sched.comments))
self.assertEqual(0, len(svc.comments))
self.show_logs()
self.show_actions()
def test_schedule_fixed_host_downtime(self):
self.print_header()
# schedule a 2-minute downtime
# downtime must be active
# consume a good result, sleep for a minute
# downtime must be active
# consume a bad result
# downtime must be active
# no notification must be found in broks
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
print("test_schedule_fixed_host_downtime initialized")
self.show_logs()
self.show_actions()
self.assertEqual(0, self.count_logs())
self.assertEqual(0, self.count_actions())
#----------------------------------------------------------------
# schedule a downtime of 10 minutes for the host
#----------------------------------------------------------------
duration = 600
now = time.time()
# fixed downtime valid for the next 10 minutes
cmd = "[%lu] SCHEDULE_HOST_DOWNTIME;test_host_0;%d;%d;1;0;%d;lausser;blablub" % (now, now, now + duration, duration)
self.sched.run_external_command(cmd)
self.sched.update_downtimes_and_comments()
print("Launch scheduler loop")
self.scheduler_loop(1, [], do_sleep=False) # push the downtime notification
self.show_actions()
print("Launch worker loop")
#self.worker_loop()
self.show_actions()
print("After both launchs")
time.sleep(20)
#----------------------------------------------------------------
# check if a downtime object exists (scheduler and host)
#----------------------------------------------------------------
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(host.downtimes))
self.assertIn(host.downtimes[0], self.sched.downtimes.values())
self.assertTrue(host.downtimes[0].fixed)
self.assertTrue(host.downtimes[0].is_in_effect)
self.assertFalse(host.downtimes[0].can_be_deleted)
self.assertEqual(1, len(self.sched.comments))
self.assertEqual(1, len(host.comments))
self.assertIn(host.comments[0], self.sched.comments.values())
self.assertEqual(host.comments[0].id, host.downtimes[0].comment_id)
self.show_logs()
self.show_actions()
print("*****************************************************************************************************************************************************************Log matching:", self.get_log_match("STARTED*"))
self.show_actions()
self.assertEqual(2, self.count_logs()) # start downt, notif downt
print(self.count_actions()) # notif" down is removed, so only donwtime
self.assertEqual(1, self.count_actions())
self.scheduler_loop(1, [], do_sleep=False)
self.show_logs()
self.show_actions()
self.assertEqual(2, self.count_logs()) # start downt, notif downt
self.clear_logs()
self.clear_actions()
#----------------------------------------------------------------
# send the host to a hard DOWN state
# check log messages, (no) notifications and eventhandlers
#----------------------------------------------------------------
self.scheduler_loop(1, [[host, 2, 'DOWN']])
self.show_logs()
self.show_actions()
self.assertEqual(2, self.count_logs()) # soft1, evt1
self.assertEqual(1, self.count_actions()) # evt1
self.clear_logs()
#--
self.scheduler_loop(1, [[host, 2, 'DOWN']])
self.show_logs()
self.show_actions()
self.assertEqual(2, self.count_logs()) # soft2, evt2
self.assertEqual(1, self.count_actions()) # evt2
self.clear_logs()
#--
self.scheduler_loop(1, [[host, 2, 'DOWN']])
self.show_logs()
self.show_actions()
self.assertEqual(2, self.count_logs()) # hard3, evt3
self.assertEqual(2, self.count_actions()) # evt3, notif"
self.clear_logs()
#--
# we have a notification, but this is blocked. it will stay in
# the actions queue because we have a notification_interval.
# it's called notif" because it is a master notification
print("DBG: host", host.state, host.state_type)
self.scheduler_loop(1, [[host, 2, 'DOWN']], do_sleep=True)
print("DBG2: host", host.state, host.state_type)
self.show_logs()
self.show_actions()
self.assertEqual(0, self.count_logs()) #
self.assertEqual(1, self.count_actions()) # notif"
self.clear_logs()
#----------------------------------------------------------------
# the host comes UP again
# check log messages, (no) notifications and eventhandlers
# a (recovery) notification was created, but has been blocked.
# should be a zombie, but was deteleted
#----------------------------------------------------------------
self.scheduler_loop(1, [[host, 0, 'UP']], do_sleep=True)
self.show_logs()
self.show_actions()
self.assertEqual(2, self.count_logs()) # hard3ok, evtok
self.assertEqual(1, self.count_actions()) # evtok, notif"
self.clear_logs()
self.clear_actions()
def test_schedule_fixed_host_downtime_with_service(self):
self.print_header()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
host.notification_interval = 0
svc.notification_interval = 0
self.show_logs()
self.show_actions()
self.assertEqual(0, self.count_logs())
self.assertEqual(0, self.count_actions())
#----------------------------------------------------------------
# schedule a downtime of 10 minutes for the host
#----------------------------------------------------------------
duration = 600
now = time.time()
cmd = "[%lu] SCHEDULE_HOST_DOWNTIME;test_host_0;%d;%d;1;0;%d;lausser;blablub" % (now, now, now + duration, duration)
self.sched.run_external_command(cmd)
self.sched.update_downtimes_and_comments()
self.scheduler_loop(1, [], do_sleep=False) # push the downtime notification
#self.worker_loop() # push the downtime notification
time.sleep(10)
#----------------------------------------------------------------
# check if a downtime object exists (scheduler and host)
# check the start downtime notification
#----------------------------------------------------------------
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(1, len(host.downtimes))
self.assertTrue(host.in_scheduled_downtime)
self.assertIn(host.downtimes[0], self.sched.downtimes.values())
self.assertTrue(host.downtimes[0].fixed)
self.assertTrue(host.downtimes[0].is_in_effect)
self.assertFalse(host.downtimes[0].can_be_deleted)
self.assertEqual(1, len(self.sched.comments))
self.assertEqual(1, len(host.comments))
self.assertIn(host.comments[0], self.sched.comments.values())
self.assertEqual(host.comments[0].id, host.downtimes[0].comment_id)
self.scheduler_loop(4, [[host, 2, 'DOWN']], do_sleep=True)
self.show_logs()
self.show_actions()
self.assertEqual(8, self.count_logs()) # start downt, notif downt, soft1, evt1, soft 2, evt2, hard 3, evt3
self.clear_logs()
self.clear_actions()
#----------------------------------------------------------------
# now the service becomes critical
# check that the host has a downtime, _not_ the service
# check logs, (no) notifications and eventhandlers
#----------------------------------------------------------------
print("now the service goes critical")
self.scheduler_loop(4, [[svc, 2, 'CRITICAL']], do_sleep=True)
self.assertEqual(1, len(self.sched.downtimes))
self.assertEqual(0, len(svc.downtimes))
self.assertFalse(svc.in_scheduled_downtime)
self.assertTrue(svc.host.in_scheduled_downtime)
self.show_logs()
self.show_actions()
# soft 1, evt1, hard 2, evt2
self.assertEqual(4, self.count_logs())
self.clear_logs()
self.clear_actions()
#----------------------------------------------------------------
# the host comes UP again
# check log messages, (no) notifications and eventhandlers
#----------------------------------------------------------------
print("now the host comes up")
self.scheduler_loop(2, [[host, 0, 'UP']], do_sleep=True)
self.show_logs()
self.show_actions()
# hard 3, eventhandler
self.assertEqual(2, self.count_logs()) # up, evt
self.clear_logs()
self.clear_actions()
#----------------------------------------------------------------
# the service becomes OK again
# check log messages, (no) notifications and eventhandlers
# check if the stop downtime notification is the only one
#----------------------------------------------------------------
self.scheduler_loop(2, [[host, 0, 'UP']], do_sleep=True)
self.assertEqual(0, len(self.sched.downtimes))
self.assertEqual(0, len(host.downtimes))
self.assertFalse(host.in_scheduled_downtime)
self.show_logs()
self.show_actions()
self.assert_log_match(1, 'HOST DOWNTIME ALERT.*STOPPED')
self.clear_logs()
self.clear_actions()
# todo
# checks return 1=warn. this means normally up
# set use_aggressive_host_checking which treats warn as down
# send host into downtime
# run service checks with result critical
# host exits downtime
# does the service send a notification like when it exts a svc dt?
# check for notifications
# host is down and in downtime. what about service eventhandlers?
def test_notification_after_cancel_flexible_svc_downtime(self):
# schedule flexible downtime
# good check
# bad check -> SOFT;1
# eventhandler SOFT;1
# bad check -> HARD;2
# downtime alert
# eventhandler HARD;2
# cancel downtime
# bad check -> HARD;2
# notification critical
#
pass
if __name__ == '__main__':
unittest.main()
| 21,609
|
Python
|
.py
| 424
| 42.492925
| 223
| 0.574831
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|
6,399
|
test_dummy.py
|
shinken-solutions_shinken/test/test_dummy.py
|
#!/usr/bin/env python
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processing of config files
#
from __future__ import absolute_import, division, print_function, unicode_literals
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_1r_1h_1s.cfg')
def test_dummy(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print("Get the hosts and services")
now = time.time()
host = self.sched.hosts.find_by_name("test_host_0")
host.checks_in_progress = []
host.act_depend_of = [] # ignore the router
router = self.sched.hosts.find_by_name("test_router_0")
router.checks_in_progress = []
router.act_depend_of = [] # ignore the router
svc = self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
svc.checks_in_progress = []
svc.act_depend_of = [] # no hostchecks on critical checkresults
self.scheduler_loop(2, [[host, 0, 'UP | value1=1 value2=2'], [router, 0, 'UP | rtt=10'], [svc, 2, 'BAD | value1=0 value2=0']])
self.assertEqual('UP', host.state)
self.assertEqual('HARD', host.state_type)
if __name__ == '__main__':
unittest.main()
| 2,107
|
Python
|
.py
| 48
| 39.291667
| 134
| 0.684878
|
shinken-solutions/shinken
| 1,133
| 337
| 226
|
AGPL-3.0
|
9/5/2024, 5:09:53 PM (Europe/Amsterdam)
|