def test_cannot_connect_to_host_control(aggregator, instance):
    host_control_url = "http://localhost:1128/SAPHostControl"
    with requests_mock.mock() as m:
        m.get(host_control_url + "/?wsdl",
              exc=requests.exceptions.ConnectTimeout)

        sap_check = SapCheck(CHECK_NAME, {}, instances=[instance])
        sap_check.check(instance)

        topology.assert_snapshot(check_id=sap_check.check_id,
                                 start_snapshot=True,
                                 stop_snapshot=True,
                                 instance_key=TopologyInstance(
                                     "sap", "LAB-SAP-001"),
                                 components=[{
                                     "id": "urn:host:/LAB-SAP-001",
                                     "type": "sap-host",
                                     "data": {
                                         "host": "LAB-SAP-001"
                                     }
                                 }])

        aggregator.assert_event(
            msg_text="",
            tags=["status:sap-host-control-error", "host:LAB-SAP-001"])

        aggregator.all_metrics_asserted()

        aggregator.assert_service_check(
            name=SapCheck.SERVICE_CHECK_NAME,
            status=AgentCheck.CRITICAL,
            message="'NoneType' object has no attribute 'items'",
            tags=[])
    def get_instance_key(self, instance):
        if 'hostip' not in instance:
            raise ConfigurationError(
                'Missing url in topology instance configuration.')

        instance_url = instance['hostip']
        return TopologyInstance(self.INSTANCE_TYPE, instance_url)
Ejemplo n.º 3
0
def test_topology(topology, instance_basic):
    mysql_check = MySql(common.CHECK_NAME, {}, {})
    mysql_check.check(instance_basic)

    topology.assert_snapshot(mysql_check.check_id, TopologyInstance("mysql", "mysql://mysql"),
                             components=[{"id": mysql_check._get_topology_hostname(common.HOST, common.PORT),
                                          "type": "mysql", "data": {}}])
Ejemplo n.º 4
0
    def get_instance_key(self, instance):
        if 'url' not in instance:
            raise ConfigurationError(
                'Missing url in topology instance configuration.')

        instance_url = urlparse(instance['url']).netloc
        return TopologyInstance(self.INSTANCE_TYPE, instance_url)
    def get_instance_key(self, instance):
        if 'url' not in instance:
            raise ConfigurationError('Missing url in configuration.')

        return TopologyInstance(self.INSTANCE_TYPE,
                                instance["url"],
                                with_snapshots=False)
Ejemplo n.º 6
0
    def get_instance_key(self, instance):
        if "name" not in instance:
            raise ConfigurationError("Missing name in topology instance configuration.")
        if "location" not in instance:
            raise ConfigurationError("Missing location in topology instance configuration.")

        name = instance["name"]
        return TopologyInstance(self.INSTANCE_TYPE, name)
def test_topology(topology, check, pg_instance):
    check.check(pg_instance)

    topology.assert_snapshot(check.check_id,
                             TopologyInstance("postgresql",
                                              "postgresql://postgresql"),
                             components=[{
                                 "id":
                                 check._get_topology_hostname(HOST),
                                 "type":
                                 "postgresql",
                                 "data": {}
                             }])
Ejemplo n.º 8
0
def test_topology(topology, check, pg_instance):
    check.check(pg_instance)

    topology.assert_snapshot(
        check.check_id,
        TopologyInstance("postgresql", "postgresql://postgresql"),
        components=[{
            "id": check._get_topology_hostname(HOST),
            "type": "postgresql",
            "data": {
                'tags': [
                    'integration-type:postgresql',
                    'integration-url:postgresql://postgresql'
                ]
            }
        }])
def test_check_run_no_sap_instances(aggregator, instance):
    # TODO this is needed because the topology retains data across tests
    topology.reset()

    host_control_url = "http://localhost:1128/SAPHostControl"
    with requests_mock.mock() as m:
        m.get(host_control_url + "/?wsdl",
              text=_read_test_file("wsdl/SAPHostAgent.wsdl"))
        m.post(host_control_url + ".cgi",
               text=_read_test_file("samples/GetCIMObject-NoResult.xml"))

        sap_check = SapCheck(CHECK_NAME, {}, instances=[instance])
        sap_check.run()
        topology.get_snapshot(sap_check.check_id)

        topology.assert_snapshot(
            check_id=sap_check.check_id,
            start_snapshot=True,
            stop_snapshot=True,
            instance_key=TopologyInstance("sap", "LAB-SAP-001"),
            components=[{
                "id": "urn:host:/LAB-SAP-001",
                "type": "sap-host",
                "data": {
                    "host": "LAB-SAP-001",
                    'tags':
                    ['integration-type:sap', 'integration-url:LAB-SAP-001'],
                    "domain": "sap",
                    "environment": "sap-prod"
                }
            }],
            relations=[],
        )

        AgentIntegrationTestUtil.assert_integration_snapshot(
            sap_check, 'sap:LAB-SAP-001')

        aggregator.assert_event(
            msg_text="Host control 'LAB-SAP-001' status update.",
            tags=["status:sap-host-control-success", "host:LAB-SAP-001"])

        aggregator.all_metrics_asserted()

        aggregator.assert_service_check(name=SapCheck.SERVICE_CHECK_NAME,
                                        status=AgentCheck.OK,
                                        message="OK",
                                        tags=[])
    def test_check(self):
        """
        Testing Servicenow check.
        """
        self.check._collect_relation_types = mock_collect_process
        self.check._batch_collect = mock_collect_process

        self.check.run()

        topo_instances = topology.get_snapshot(self.check.check_id)
        self.assertEqual(len(topo_instances['components']), 0)
        self.assertEqual(len(topo_instances['relations']), 0)

        self.assertEqual(
            self.check._get_instance_key(),
            TopologyInstance('servicenow_cmdb',
                             'https://instance.service-now.com'))

        AgentIntegrationTestUtil.assert_integration_snapshot(
            self.check, 'servicenow_cmdb:https://instance.service-now.com')
def test_check_run_no_sap_instances(aggregator, instance):
    # TODO this is needed because the topology retains data across tests
    topology.reset()

    host_control_url = "http://localhost:1128/SAPHostControl"
    with requests_mock.mock() as m:
        m.get(host_control_url + "/?wsdl",
              text=_read_test_file("wsdl/HostControl.wsdl"))
        m.post(host_control_url + ".cgi",
               text=_read_test_file("samples/GetCIMObject-NoResult.xml"))

        sap_check = SapCheck(CHECK_NAME, {}, instances=[instance])
        sap_check.check(instance)

        topology.assert_snapshot(check_id=sap_check.check_id,
                                 start_snapshot=True,
                                 stop_snapshot=True,
                                 instance_key=TopologyInstance(
                                     "sap", "LAB-SAP-001"),
                                 components=[{
                                     "id": "urn:host:/LAB-SAP-001",
                                     "type": "sap-host",
                                     "data": {
                                         "host": "LAB-SAP-001"
                                     }
                                 }])

        aggregator.assert_event(
            msg_text="",
            tags=["status:sap-host-control-success", "host:LAB-SAP-001"])

        aggregator.all_metrics_asserted()

        aggregator.assert_service_check(name=SapCheck.SERVICE_CHECK_NAME,
                                        status=AgentCheck.OK,
                                        message="OK",
                                        tags=[])
 def get_instance_key(self, instance):
     return TopologyInstance(Instance.INSTANCE_TYPE, instance["url"])
Ejemplo n.º 13
0
 def get_instance_key(self, instance):
     return TopologyInstance(self.INSTANCE_TYPE, self.account_id)
def test_collect_only_hosts_create_service_https(aggregator, https_instance):
    """
        Should return the proper host location as defined in the config and doesn't care about WSDL host location
    """
    # TODO this is needed because the topology retains data across tests
    topology.reset()

    host_control_url = "https://localhost:1129/SAPHostControl"
    with requests_mock.mock() as m:
        m.get(host_control_url + "/?wsdl", text=_read_test_file("wsdl/SAPHostAgent.wsdl"))
        m.post(host_control_url + ".cgi", text=_read_test_file("samples/GetCIMObject.xml"))

        sap_check = SapCheck(CHECK_NAME, {}, instances=[https_instance])
        sap_check._get_config(https_instance)
        sap_check._collect_hosts()

        assert sap_check.verify is False

        topology.assert_snapshot(
            check_id=sap_check.check_id,
            start_snapshot=False,
            stop_snapshot=False,
            instance_key=TopologyInstance("sap", "LAB-SAP-001"),
            components=[
                {"id": "urn:host:/LAB-SAP-001", "type": "sap-host",
                 "data": {"host": "LAB-SAP-001",
                          'tags': ['customer:Stackstate', 'foo:bar', 'integration-type:sap',
                                   'integration-url:LAB-SAP-001'],
                          "domain": None, "environment": None}},
                {"id": "urn:sap:/instance:LAB-SAP-001:67",
                 "type": "sap-instance",
                 "data": {"host": "LAB-SAP-001",
                          "labels": [],
                          'tags': ['customer:Stackstate', 'foo:bar', 'integration-type:sap',
                                   'integration-url:LAB-SAP-001'],
                          "name": "CDA",
                          "sid": "CDA",
                          "system_number": "67",
                          "type": "Solution Manager Diagnostic Agent",
                          "version": "753, patch 200, changelist 1844229",
                          "domain": None,
                          "environment": None}},
                {"id": "urn:sap:/instance:LAB-SAP-001:00",
                 "type": "sap-instance",
                 "data": {"host": "LAB-SAP-001",
                          "labels": [],
                          'tags': ['customer:Stackstate', 'foo:bar', 'integration-type:sap',
                                   'integration-url:LAB-SAP-001'],
                          "name": "DON",
                          "sid": "DON",
                          "system_number": "00",
                          "type": "ABAP Instance",
                          "version": "753, patch 401, changelist 1927964",
                          "domain": None,
                          "environment": None}},
                {"id": "urn:sap:/instance:LAB-SAP-001:01",
                 "type": "sap-instance",
                 "data": {"host": "LAB-SAP-001",
                          "labels": [],
                          'tags': ['customer:Stackstate', 'foo:bar', 'integration-type:sap',
                                   'integration-url:LAB-SAP-001'],
                          "name": "DON",
                          "sid": "DON",
                          "system_number": "01",
                          "type": "Central Services Instance",
                          "version": "753, patch 401, changelist 1927964",
                          "domain": None,
                          "environment": None}}
            ],
            relations=[
                {'data': {"domain": None, "environment": None, "tags": ['customer:Stackstate', 'foo:bar']},
                 'source_id': 'urn:sap:/instance:LAB-SAP-001:67',
                 'target_id': 'urn:host:/LAB-SAP-001',
                 'type': 'is hosted on'},
                {'data': {"domain": None, "environment": None, "tags": ['customer:Stackstate', 'foo:bar']},
                 'source_id': 'urn:sap:/instance:LAB-SAP-001:00',
                 'target_id': 'urn:host:/LAB-SAP-001',
                 'type': 'is hosted on'},
                {'data': {"domain": None, "environment": None, "tags": ['customer:Stackstate', 'foo:bar']},
                 'source_id': 'urn:sap:/instance:LAB-SAP-001:01',
                 'target_id': 'urn:host:/LAB-SAP-001',
                 'type': 'is hosted on'}
            ]
        )

        aggregator.assert_event(
            msg_text="",
            tags=[
                "status:sap-host-control-success",
                "host:LAB-SAP-001"
            ]
        )

        aggregator.all_metrics_asserted()
Ejemplo n.º 15
0
 def get_instance_key(self, instance):
     if "organization_id" not in instance:
         raise ConfigurationError(
             "Missing 'organization' in instance configuration.")
     return TopologyInstance(self.INSTANCE_TYPE, str(self.organization_id))
 def get_instance_key(self, instance_info):
     return TopologyInstance(self.INSTANCE_TYPE,
                             str(self.get_account_id(instance_info)))
 def get_instance_key(self, instance):
     return TopologyInstance("postgresql", "postgresql://postgresql")
def test_collect_processes(aggregator, instance):
    # TODO this is needed because the topology retains data across tests
    topology.reset()

    instance_id = "00"
    host_agent_url = "http://localhost:50013/"
    with requests_mock.mock() as m:
        m.get(host_agent_url + "SAPHostAgent/?wsdl",
              text=_read_test_file("wsdl/HostAgent.wsdl"))
        m.post(host_agent_url,
               text=_read_test_file("samples/GetProcessList.xml"))

        sap_check = SapCheck(CHECK_NAME, {}, instances=[instance])
        sap_check._get_config(instance)
        sap_check._collect_processes(instance_id,
                                     sap_check._get_proxy(instance_id))

        topology.assert_snapshot(
            check_id=sap_check.check_id,
            start_snapshot=False,
            stop_snapshot=False,
            instance_key=TopologyInstance("sap", "LAB-SAP-001"),
            components=[{
                'data': {
                    'description': 'Dispatcher',
                    'elapsedtime': '119:16:01',
                    'host': 'LAB-SAP-001',
                    'labels': [],
                    'name': 'disp+work.EXE',
                    'pid': 4392,
                    'starttime': '2020 01 22 12:52:29'
                },
                'id': 'urn:process:/LAB-SAP-001:00:4392',
                'type': 'sap-process'
            }, {
                'data': {
                    'description': 'IGS Watchdog',
                    'elapsedtime': '119:16:01',
                    'host': 'LAB-SAP-001',
                    'labels': [],
                    'name': 'igswd.EXE',
                    'pid': 11088,
                    'starttime': '2020 01 22 12:52:29'
                },
                'id': 'urn:process:/LAB-SAP-001:00:11088',
                'type': 'sap-process'
            }, {
                'data': {
                    'description': 'Gateway',
                    'elapsedtime': '119:16:01',
                    'host': 'LAB-SAP-001',
                    'labels': [],
                    'name': 'gwrd',
                    'pid': 9512,
                    'starttime': '2020 01 22 12:52:29'
                },
                'id': 'urn:process:/LAB-SAP-001:00:9512',
                'type': 'sap-process'
            }, {
                'data': {
                    'description': 'ICM',
                    'elapsedtime': '119:16:01',
                    'host': 'LAB-SAP-001',
                    'labels': [],
                    'name': 'icman',
                    'pid': 6584,
                    'starttime': '2020 01 22 12:52:29'
                },
                'id': 'urn:process:/LAB-SAP-001:00:6584',
                'type': 'sap-process'
            }],
            relations=[{
                'data': {},
                'source_id': 'urn:process:/LAB-SAP-001:00:4392',
                'target_id': 'urn:sap:/instance:LAB-SAP-001:00',
                'type': 'runs on'
            }, {
                'data': {},
                'source_id': 'urn:process:/LAB-SAP-001:00:11088',
                'target_id': 'urn:sap:/instance:LAB-SAP-001:00',
                'type': 'runs on'
            }, {
                'data': {},
                'source_id': 'urn:process:/LAB-SAP-001:00:9512',
                'target_id': 'urn:sap:/instance:LAB-SAP-001:00',
                'type': 'runs on'
            }, {
                'data': {},
                'source_id': 'urn:process:/LAB-SAP-001:00:6584',
                'target_id': 'urn:sap:/instance:LAB-SAP-001:00',
                'type': 'runs on'
            }])

        aggregator.assert_event(msg_text="Running",
                                tags=[
                                    "status:SAPControl-GREEN",
                                    "pid:4392",
                                    "instance_id:" + instance_id,
                                    "starttime:2020 01 22 12:52:29",
                                ])
        aggregator.assert_event(msg_text="Running",
                                tags=[
                                    "status:SAPControl-GREEN",
                                    "pid:11088",
                                    "instance_id:" + instance_id,
                                    "starttime:2020 01 22 12:52:29",
                                ])
        aggregator.assert_event(msg_text="Running",
                                tags=[
                                    "status:SAPControl-GREEN",
                                    "pid:9512",
                                    "instance_id:" + instance_id,
                                    "starttime:2020 01 22 12:52:29",
                                ])
        aggregator.assert_event(msg_text="Running",
                                tags=[
                                    "status:SAPControl-GRAY",
                                    "pid:6584",
                                    "instance_id:" + instance_id,
                                    "starttime:2020 01 22 12:52:29",
                                ])

        aggregator.all_metrics_asserted()
Ejemplo n.º 19
0
 def get_instance_key(self, instance_info):
     return TopologyInstance(self.INSTANCE_TYPE, str(instance_info.health_file))
def test_collect_processes(aggregator, instance):
    # TODO this is needed because the topology retains data across tests
    topology.reset()

    instance_id = "00"
    host_control_url = "http://localhost:1128/SAPHostControl"
    with requests_mock.mock() as m:
        m.get(host_control_url + "/?wsdl", text=_read_test_file("wsdl/SAPHostAgent.wsdl"))
        m.post(host_control_url + ".cgi", text=_read_test_file("samples/GetProcessList.xml"))

        sap_check = SapCheck(CHECK_NAME, {}, instances=[instance])
        sap_check._get_config(instance)
        sap_check._collect_processes(instance_id, sap_check._get_proxy(instance_id))

        topology.assert_snapshot(
            check_id=sap_check.check_id,
            start_snapshot=False,
            stop_snapshot=False,
            instance_key=TopologyInstance("sap", "LAB-SAP-001"),
            components=[
                {'data': {'description': 'Dispatcher',
                          'elapsedtime': '0:56:22',
                          'host': 'LAB-SAP-001',
                          'labels': [],
                          'tags': ['integration-type:sap', 'integration-url:LAB-SAP-001'],
                          'name': 'disp+work.EXE',
                          'pid': 5972,
                          'starttime': '2020 07 31 08:37:19',
                          "domain": "sap", "environment": "sap-prod"},
                 'id': 'urn:process:/LAB-SAP-001:00:5972',
                 'type': 'sap-process'},
                {'data': {'description': 'IGS Watchdog',
                          'elapsedtime': '0:56:22',
                          'host': 'LAB-SAP-001',
                          'labels': [],
                          'tags': ['integration-type:sap', 'integration-url:LAB-SAP-001'],
                          'name': 'igswd.EXE',
                          'pid': 15564,
                          'starttime': '2020 07 31 08:37:19',
                          "domain": "sap", "environment": "sap-prod"},
                 'id': 'urn:process:/LAB-SAP-001:00:15564',
                 'type': 'sap-process'},
                {'data': {'description': 'Gateway',
                          'elapsedtime': '0:56:21',
                          'host': 'LAB-SAP-001',
                          'labels': [],
                          'tags': ['integration-type:sap', 'integration-url:LAB-SAP-001'],
                          'name': 'gwrd',
                          'pid': 16624,
                          'starttime': '2020 07 31 08:37:20',
                          "domain": "sap", "environment": "sap-prod"},
                 'id': 'urn:process:/LAB-SAP-001:00:16624',
                 'type': 'sap-process'},
                {'data': {'description': 'ICM',
                          'elapsedtime': '0:56:21',
                          'host': 'LAB-SAP-001',
                          'labels': [],
                          'tags': ['integration-type:sap', 'integration-url:LAB-SAP-001'],
                          'name': 'icman',
                          'pid': 11508,
                          'starttime': '2020 07 31 08:37:20',
                          "domain": "sap", "environment": "sap-prod"},
                 'id': 'urn:process:/LAB-SAP-001:00:11508',
                 'type': 'sap-process'}
            ],
            relations=[
                {'data': {"domain": "sap", "environment": "sap-prod", "tags": []},
                 'source_id': 'urn:process:/LAB-SAP-001:00:5972',
                 'target_id': 'urn:sap:/instance:LAB-SAP-001:00',
                 'type': 'runs on'},
                {'data': {"domain": "sap", "environment": "sap-prod", "tags": []},
                 'source_id': 'urn:process:/LAB-SAP-001:00:15564',
                 'target_id': 'urn:sap:/instance:LAB-SAP-001:00',
                 'type': 'runs on'},
                {'data': {"domain": "sap", "environment": "sap-prod", "tags": []},
                 'source_id': 'urn:process:/LAB-SAP-001:00:16624',
                 'target_id': 'urn:sap:/instance:LAB-SAP-001:00',
                 'type': 'runs on'},
                {'data': {"domain": "sap", "environment": "sap-prod", "tags": []},
                 'source_id': 'urn:process:/LAB-SAP-001:00:11508',
                 'target_id': 'urn:sap:/instance:LAB-SAP-001:00',
                 'type': 'runs on'}
            ]
        )

        aggregator.assert_event(
            msg_text="Running",
            tags=[
                "status:SAPControl-GREEN",
                "pid:5972",
                "instance_id:" + instance_id,
                "starttime:2020 07 31 08:37:19",
            ]
        )
        aggregator.assert_event(
            msg_text="Running",
            tags=[
                "status:SAPControl-GREEN",
                "pid:15564",
                "instance_id:" + instance_id,
                "starttime:2020 07 31 08:37:19",
            ]
        )
        aggregator.assert_event(
            msg_text="Running",
            tags=[
                "status:SAPControl-GREEN",
                "pid:16624",
                "instance_id:" + instance_id,
                "starttime:2020 07 31 08:37:20",
            ]
        )
        aggregator.assert_event(
            msg_text="Running",
            tags=[
                "status:SAPControl-GREEN",
                "pid:11508",
                "instance_id:" + instance_id,
                "starttime:2020 07 31 08:37:20",
            ]
        )

        aggregator.all_metrics_asserted()
def test_collect_databases(aggregator, instance):
    # TODO this is needed because the topology retains data across tests
    topology.reset()

    host_control_url = "http://localhost:1128/SAPHostControl"
    with requests_mock.mock() as m:
        m.get(host_control_url + "/?wsdl",
              text=_read_test_file("wsdl/HostControl.wsdl"))
        m.post(host_control_url + ".cgi",
               text=_read_test_file("samples/ListDatabases.xml"))

        sap_check = SapCheck(CHECK_NAME, {}, instances=[instance])
        sap_check._get_config(instance)
        sap_check._collect_databases()

        topology.assert_snapshot(
            check_id=sap_check.check_id,
            start_snapshot=False,
            stop_snapshot=False,
            instance_key=TopologyInstance("sap", "LAB-SAP-001"),
            components=[{
                'type': 'sap-database',
                'id': 'urn:db:/LAB-SAP-001:DON',
                'data': {
                    'vendor': 'ora',
                    'name': 'DON',
                    'type': 'ora',
                    'host': 'lab-sap-001',
                    'version': '18.0.0.0.0',
                    'labels': []
                }
            }, {
                'type': 'sap-database-component',
                'id': 'urn:sap:/db_component:LAB-SAP-001:DON:Instance',
                'data': {
                    'host': 'LAB-SAP-001',
                    'description': 'Instance',
                    'database_name': 'DON',
                    'name': 'Instance',
                    'labels': []
                }
            }, {
                'type': 'sap-database-component',
                'id': 'urn:sap:/db_component:LAB-SAP-001:DON:Database',
                'data': {
                    'host': 'LAB-SAP-001',
                    'description': 'Database',
                    'database_name': 'DON',
                    'name': 'Database',
                    'labels': []
                }
            }, {
                'type': 'sap-database-component',
                'id': 'urn:sap:/db_component:LAB-SAP-001:DON:Archiver',
                'data': {
                    'host': 'LAB-SAP-001',
                    'description': 'Archiver',
                    'database_name': 'DON',
                    'name': 'Archiver',
                    'labels': []
                }
            }, {
                'type': 'sap-database-component',
                'id': 'urn:sap:/db_component:LAB-SAP-001:DON:Listener',
                'data': {
                    'host': 'LAB-SAP-001',
                    'description': 'Listener',
                    'database_name': 'DON',
                    'name': 'Listener',
                    'labels': []
                }
            }],
            relations=[{
                'type': 'is hosted on',
                'data': {},
                'source_id': 'urn:db:/LAB-SAP-001:DON',
                'target_id': 'urn:host:/LAB-SAP-001'
            }, {
                'type': 'runs on',
                'data': {},
                'source_id': 'urn:sap:/db_component:LAB-SAP-001:DON:Instance',
                'target_id': 'urn:db:/LAB-SAP-001:DON'
            }, {
                'type': 'runs on',
                'data': {},
                'source_id': 'urn:sap:/db_component:LAB-SAP-001:DON:Database',
                'target_id': 'urn:db:/LAB-SAP-001:DON'
            }, {
                'type': 'runs on',
                'data': {},
                'source_id': 'urn:sap:/db_component:LAB-SAP-001:DON:Archiver',
                'target_id': 'urn:db:/LAB-SAP-001:DON'
            }, {
                'type': 'runs on',
                'data': {},
                'source_id': 'urn:sap:/db_component:LAB-SAP-001:DON:Listener',
                'target_id': 'urn:db:/LAB-SAP-001:DON'
            }])

        aggregator.assert_event(msg_text="",
                                tags=[
                                    "status:SAPHostControl-DB-RUNNING",
                                    "database_name:DON",
                                ])

        aggregator.assert_event(msg_text="",
                                tags=[
                                    "status:SAPHostControl-DB-RUNNING",
                                    "database_component_name:Instance",
                                ])
        aggregator.assert_event(msg_text="",
                                tags=[
                                    "status:SAPHostControl-DB-RUNNING",
                                    "database_component_name:Database",
                                ])
        aggregator.assert_event(msg_text="",
                                tags=[
                                    "status:SAPHostControl-DB-RUNNING",
                                    "database_component_name:Archiver",
                                ])
        aggregator.assert_event(msg_text="",
                                tags=[
                                    "status:SAPHostControl-DB-RUNNING",
                                    "database_component_name:Listener",
                                ])

        aggregator.all_metrics_asserted()
def test_collect_only_hosts(aggregator, instance):
    # TODO this is needed because the topology retains data across tests
    topology.reset()

    host_control_url = "http://localhost:1128/SAPHostControl"
    with requests_mock.mock() as m:
        m.get(host_control_url + "/?wsdl",
              text=_read_test_file("wsdl/HostControl.wsdl"))
        m.post(host_control_url + ".cgi",
               text=_read_test_file("samples/GetCIMObject.xml"))

        sap_check = SapCheck(CHECK_NAME, {}, instances=[instance])
        sap_check._get_config(instance)
        sap_check._collect_hosts()

        topology.assert_snapshot(
            check_id=sap_check.check_id,
            start_snapshot=False,
            stop_snapshot=False,
            instance_key=TopologyInstance("sap", "LAB-SAP-001"),
            components=[{
                "id": "urn:host:/LAB-SAP-001",
                "type": "sap-host",
                "data": {
                    "host": "LAB-SAP-001"
                }
            }, {
                "id": "urn:sap:/instance:LAB-SAP-001:67",
                "type": "sap-instance",
                "data": {
                    "host": "LAB-SAP-001",
                    "labels": [],
                    "name": "CDA",
                    "sid": "CDA",
                    "system_number": "67",
                    "type": "Solution Manager Diagnostic Agent",
                    "version": "753, patch 200, changelist 1844229"
                }
            }, {
                "id": "urn:sap:/instance:LAB-SAP-001:00",
                "type": "sap-instance",
                "data": {
                    "host": "LAB-SAP-001",
                    "labels": [],
                    "name": "DON",
                    "sid": "DON",
                    "system_number": "00",
                    "type": "ABAP Instance",
                    "version": "753, patch 401, changelist 1927964"
                }
            }, {
                "id": "urn:sap:/instance:LAB-SAP-001:01",
                "type": "sap-instance",
                "data": {
                    "host": "LAB-SAP-001",
                    "labels": [],
                    "name": "DON",
                    "sid": "DON",
                    "system_number": "01",
                    "type": "Central Services Instance",
                    "version": "753, patch 401, changelist 1927964"
                }
            }],
            relations=[{
                'data': {},
                'source_id': 'urn:sap:/instance:LAB-SAP-001:67',
                'target_id': 'urn:host:/LAB-SAP-001',
                'type': 'is hosted on'
            }, {
                'data': {},
                'source_id': 'urn:sap:/instance:LAB-SAP-001:00',
                'target_id': 'urn:host:/LAB-SAP-001',
                'type': 'is hosted on'
            }, {
                'data': {},
                'source_id': 'urn:sap:/instance:LAB-SAP-001:01',
                'target_id': 'urn:host:/LAB-SAP-001',
                'type': 'is hosted on'
            }])

        aggregator.assert_event(
            msg_text="",
            tags=["status:sap-host-control-success", "host:LAB-SAP-001"])

        aggregator.all_metrics_asserted()
    def get_instance_key(self, instance):
        if "host" not in instance:
            raise ConfigurationError(
                "Missing 'host' in instance configuration.")

        return TopologyInstance(self.INSTANCE_TYPE, instance["host"])
class TestSplunkCheck(unittest.TestCase):
    CHECK_NAME = "splunk"

    instance = {
        'url': 'http://localhost:8089',
        'authentication': {
            'basic_auth': {
                'username': "******",
                'password': "******"
            }
        },
        'component_saved_searches': [],
        'relation_saved_searches': []
    }

    instance_key = TopologyInstance("splunk", "http://localhost:8089")

    def setUp(self):
        """
        Initialize and patch the check, i.e.
        """
        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {},
                                          [self.instance])
        topology.reset()
        aggregator.reset()
        self.check.commit_state(None)

    def test_no_topology_defined(self):
        assert self.check.run() == ''
        topology.assert_snapshot(self.check.check_id, self.instance_key, True,
                                 True)

    def test_components_and_relation_data(self):
        instance = {
            'url': 'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'component_saved_searches': [{
                "name": "components",
                "parameters": {}
            }],
            'relation_saved_searches': [{
                "name": "relations",
                "parameters": {}
            }],
            'tags': ['mytag', 'mytag2']
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        assert self.check.run() == ''
        topology.assert_snapshot(
            self.check.check_id, self.instance_key, True, True, [{
                'id': u'vm_2_1',
                'type': u'vm',
                'data': {
                    u"running":
                    True,
                    u"_time":
                    "2017-03-06T14:55:54.000+00:00",
                    u"label.label1Key":
                    "label1Value",
                    u"tags": [
                        'integration-type:splunk',
                        'integration-url:http://localhost:8089', 'mytag',
                        'mytag2', 'result_tag1'
                    ]
                }
            }, {
                "id": u"server_2",
                "type": u"server",
                "data": {
                    u"description":
                    "My important server 2",
                    u"_time":
                    "2017-03-06T14:55:54.000+00:00",
                    u"label.label2Key":
                    "label2Value",
                    u"tags": [
                        'integration-type:splunk',
                        'integration-url:http://localhost:8089', 'mytag',
                        'mytag2', 'result_tag2'
                    ]
                }
            }], [{
                "type": u"HOSTED_ON",
                "source_id": u"vm_2_1",
                "target_id": u"server_2",
                "data": {
                    u"description": "Some relation",
                    u"_time": "2017-03-06T15:10:57.000+00:00",
                    "tags": ['mytag', 'mytag2']
                }
            }])

        service_checks = aggregator.service_checks(
            SplunkTopology.SERVICE_CHECK_NAME)
        self.assertEqual(service_checks[0].status, 0)

    def test_no_snapshot(self):
        instance = {
            'url': 'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'snapshot': False,
            'component_saved_searches': [{
                "name": "components",
                "parameters": {}
            }],
            'relation_saved_searches': [],
            'tags': ['mytag', 'mytag2']
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        assert self.check.run() == ''
        topology.assert_snapshot(
            self.check.check_id, self.instance_key, False, False, [{
                'id': u'vm_2_1',
                'type': u'vm',
                'data': {
                    u"running":
                    True,
                    u"_time":
                    "2017-03-06T14:55:54.000+00:00",
                    u"label.label1Key":
                    "label1Value",
                    u"tags": [
                        'integration-type:splunk',
                        'integration-url:http://localhost:8089', 'mytag',
                        'mytag2', 'result_tag1'
                    ]
                }
            }, {
                "id": u"server_2",
                "type": u"server",
                "data": {
                    u"description":
                    "My important server 2",
                    u"_time":
                    "2017-03-06T14:55:54.000+00:00",
                    u"label.label2Key":
                    "label2Value",
                    u"tags": [
                        'integration-type:splunk',
                        'integration-url:http://localhost:8089', 'mytag',
                        'mytag2', 'result_tag2'
                    ]
                }
            }], [])

        service_checks = aggregator.service_checks(
            SplunkTopology.SERVICE_CHECK_NAME)
        self.assertEqual(service_checks[0].status, 0)

    def test_minimal_topology(self):
        instance = {
            'url':
            'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'snapshot':
            True,
            'component_saved_searches': [{
                "name": "minimal_components",
                "parameters": {}
            }],
            'relation_saved_searches': [{
                "name": "minimal_relations",
                "parameters": {}
            }],
            'tags': ['mytag', 'mytag2']
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        assert self.check.run() == ''
        topology.assert_snapshot(
            self.check.check_id, self.instance_key, True, True, [{
                "id": u"vm_2_1",
                "type": u"vm",
                "data": {
                    u"tags": [
                        'integration-type:splunk',
                        'integration-url:http://localhost:8089', 'mytag',
                        'mytag2'
                    ]
                }
            }, {
                'id': u"server_2",
                "type": u'server',
                "data": {
                    u"tags": [
                        'integration-type:splunk',
                        'integration-url:http://localhost:8089', 'mytag',
                        'mytag2'
                    ]
                }
            }], [{
                "type": u"HOSTED_ON",
                "source_id": u"vm_2_1",
                "target_id": u"server_2",
                "data": {
                    "tags": ['mytag', 'mytag2']
                }
            }])

        service_checks = aggregator.service_checks(
            SplunkTopology.SERVICE_CHECK_NAME)
        self.assertEqual(service_checks[0].status, 0)

    def test_incomplete_topology(self):
        instance = {
            'url':
            'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'snapshot':
            True,
            'component_saved_searches': [{
                "name": "incomplete_components",
                "parameters": {}
            }],
            'relation_saved_searches': [{
                "name": "mincomplete_relations",
                "parameters": {}
            }],
            'tags': ['mytag', 'mytag2']
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        assert self.check.run() != ''

        service_checks = aggregator.service_checks(
            SplunkTopology.SERVICE_CHECK_NAME)
        self.assertEqual(service_checks[0].status, 2)

    def test_partially_incomplete(self):
        instance = {
            'url':
            'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'snapshot':
            True,
            'component_saved_searches': [{
                "name": "partially_incomplete_components",
                "parameters": {}
            }],
            'relation_saved_searches': [{
                "name": "partially_incomplete_relations",
                "parameters": {}
            }],
            'tags': ['mytag', 'mytag2']
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        assert self.check.run() == ''
        topology.assert_snapshot(
            self.check.check_id, self.instance_key, True, True, [{
                "id": u"vm_2_1",
                "type": u"vm",
                "data": {
                    u"tags": [
                        'integration-type:splunk',
                        'integration-url:http://localhost:8089', 'mytag',
                        'mytag2'
                    ]
                }
            }], [{
                "type": u"HOSTED_ON",
                "source_id": u"vm_2_1",
                "target_id": u"server_2",
                "data": {
                    "tags": ['mytag', 'mytag2']
                }
            }])

        service_checks = aggregator.service_checks(
            SplunkTopology.SERVICE_CHECK_NAME)

        self.assertEqual(service_checks[0].status, 1)
        self.assertEqual(
            service_checks[0].message,
            "The saved search 'partially_incomplete_components' contained 1 incomplete records"
        )
        self.assertEqual(service_checks[1].status, 1)
        self.assertEqual(
            service_checks[1].message,
            "The saved search 'partially_incomplete_relations' contained 1 incomplete records"
        )

    def test_upgrade_error_default_polling_interval(self):
        instance = {
            'url': 'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'snapshot': True,
            'component_saved_searches': [{
                "name": "components",
                "parameters": {}
            }],
            'relation_saved_searches': [{
                "name": "relations",
                "parameters": {}
            }],
            'tags': ['mytag', 'mytag2']
        }

        init_config = {'default_polling_interval_seconds': 15}

        self.check = MockedSplunkTopology(self.CHECK_NAME, init_config, {},
                                          [instance])
        assert "deprecated config `init_config.default_polling_interval_seconds` found." in self.check.run(
        )

    def test_upgrade_error_polling_interval(self):
        instance = {
            'url': 'http://localhost:8089',
            'polling_interval_seconds': 15,
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'snapshot': True,
            'component_saved_searches': [{
                "name": "components",
                "parameters": {}
            }],
            'relation_saved_searches': [{
                "name": "relations",
                "parameters": {}
            }],
            'tags': ['mytag', 'mytag2']
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        assert "deprecated config `polling_interval_seconds` found." in self.check.run(
        )

    def test_handle_saved_search_run_error(self):
        instance = {
            'url':
            'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'component_saved_searches': [{
                "name": "dispatch_exception",
                "parameters": {}
            }],
            'relation_saved_searches': [],
            'tags': ['mytag', 'mytag2']
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        assert "BOOM" in self.check.run()

        service_checks = aggregator.service_checks(
            SplunkTopology.SERVICE_CHECK_NAME)
        self.assertEqual(service_checks[0].status, 2)

    def test_ignore_saved_search_run_error(self):
        instance = {
            'url':
            'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'component_saved_searches': [{
                "name": "dispatch_exception",
                "parameters": {}
            }],
            'relation_saved_searches': [],
            'ignore_saved_search_errors':
            True,
            'tags': ['mytag', 'mytag2']
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        assert self.check.run() == ''

        service_checks = aggregator.service_checks(
            SplunkTopology.SERVICE_CHECK_NAME)
        self.assertEqual(service_checks[0].status, 2)

    def test_default_parameters(self):
        instance = {
            'url': 'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'component_saved_searches': [{
                "name": "components"
            }],
            'relation_saved_searches': [{
                "name": "relations"
            }]
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        assert self.check.run() == ''

        assert self.check.instance_data.splunk_client._dispatch_parameters == {
            'dispatch.now': True,
            'force_dispatch': True,
            'output_mode': 'json'
        }

    def test_non_default_parameters(self):
        instance = {
            'url': 'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'component_saved_searches': [{
                "name": "components"
            }],
            'relation_saved_searches': [{
                "name": "relations"
            }]
        }

        init_config = {'default_parameters': {'respect': 'me'}}
        self.check = MockedSplunkTopology(self.CHECK_NAME, init_config, {},
                                          [instance])
        assert self.check.run() == ''

        assert self.check.instance_data.splunk_client._dispatch_parameters == {
            'respect': 'me',
            'output_mode': 'json'
        }

    def test_non_default_parameters_override(self):
        instance = {
            'url':
            'http://localhost:8089',
            'authentication': {
                'basic_auth': {
                    'username': "******",
                    'password': "******"
                }
            },
            'component_saved_searches': [{
                "name": "components",
                "parameters": {
                    "respect": "me"
                }
            }],
            'relation_saved_searches': [{
                "name": "relations",
                "parameters": {
                    "respect": "me"
                }
            }]
        }

        init_config = {'default_parameters': {'default_should': 'be_ignore'}}
        self.check = MockedSplunkTopology(self.CHECK_NAME, init_config, {},
                                          [instance])
        assert self.check.run() == ''

        assert self.check.instance_data.splunk_client._dispatch_parameters == {
            'respect': 'me',
            'output_mode': 'json'
        }

    def test_check_valid_initial_token(self):
        """
            Splunk topology check should work with valid initial token
        """

        instance = {
            'url': 'http://localhost:8089',
            'authentication': {
                'token_auth': {
                    'name': "admin",
                    'initial_token':
                    "dsfdgfhgjhkjuyr567uhfe345ythu7y6tre456sdx",
                    'audience': "search",
                    'renewal_days': 10
                }
            },
            'component_saved_searches': [{
                "name": "components",
                "parameters": {}
            }],
            'relation_saved_searches': [],
            'tags': ['mytag', 'mytag2']
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        assert self.check.run() == ''

    def test_check_invalid_initial_token(self):
        """
            Splunk check should not work with invalid initial token and stop the check
        """
        instance = {
            'url': 'http://localhost:8089',
            'authentication': {
                'token_auth': {
                    'name': "admin",
                    'initial_token':
                    "dsfdgfhgjhkjuyr567uhfe345ythu7y6tre456sdx",
                    'audience': "search",
                    'renewal_days': 10
                }
            },
            'component_saved_searches': [{
                "name": "components",
                "parameters": {}
            }],
            'relation_saved_searches': [],
            'tags': ['mytag', 'mytag2']
        }

        self.check = MockedSplunkTopology(self.CHECK_NAME, {}, {}, [instance])
        # Run once to initialize
        assert self.check.run() == ''
        aggregator.reset()

        self.check.instance_data.splunk_client.invalid_token = True
        assert self.check.run() == ''

        msg = "Current in use authentication token is expired. Please provide a valid token in the YAML and restart " \
              "the Agent"

        service_checks = aggregator.service_checks(
            SplunkTopology.SERVICE_CHECK_NAME)
        self.assertEqual(service_checks[0].status, 2)
        self.assertEqual(service_checks[0].message, msg)