source: nscp/scripts/python/test_nsca.py @ b175d61

0.4.00.4.10.4.2
Last change on this file since b175d61 was b175d61, checked in by Michael Medin <michael@…>, 17 months ago
  • Fixed a race condition in the python unit test script
  • Property mode set to 100644
File size: 9.4 KB
Line 
1from NSCP import Settings, Registry, Core, log, status, log_error, sleep
2from test_helper import BasicTest, TestResult, Callable, setup_singleton, install_testcases, init_testcases, shutdown_testcases
3import plugin_pb2
4from types import *
5import socket
6import uuid
7import unicodedata
8#import _thread
9#sync = _thread.allocate_lock()
10
11import threading
12sync = threading.RLock()
13
14core = Core.get()
15
16def isOpen(ip, port):
17        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
18        try:
19                s.connect((ip, int(port)))
20                s.shutdown(2)
21                return True
22        except:
23                return False
24
25class NSCAMessage:
26        uuid = None
27        source = None
28        command = None
29        status = None
30        message = None
31        perfdata = None
32        got_response = False
33        got_simple_response = False
34
35        def __init__(self, command):
36                if type(command) == 'unicode':
37                        try:
38                                self.uuid = command.decode('ascii', 'replace')
39                        except UnicodeDecodeError:
40                                self.uuid = command
41                else:
42                        self.uuid = command
43                #self.uuid = unicodedata.normalize('NFKD', command).encode('ascii','ignore')
44                self.command = command
45                self.uuid = None
46                self.source = None
47                self.status = None
48                self.message = None
49                self.perfdata = None
50                self.got_response = False
51                self.got_simple_response = False
52               
53               
54        def copy_changed_attributes(self, other):
55                if other.source:
56                        self.source = other.source
57                if other.command:
58                        self.command = other.command
59                if other.status:
60                        self.status = other.status
61                if other.message:
62                        self.message = other.message
63                if other.perfdata:
64                        self.perfdata = other.perfdata
65                if other.got_simple_response:
66                        self.got_simple_response = True
67       
68        def __str__(self):
69                return 'Message: %s (%s, %s, %s)'%(self.uuid, self.source, self.command, self.status)
70
71class NSCAServerTest(BasicTest):
72        instance = None
73        key = ''
74        reg = None
75        _responses = {}
76       
77        def has_response(self, id):
78                with sync:
79                        return id in self._responses
80       
81        def get_response(self, id):
82                with sync:
83                        if id in self._responses:
84                                return self._responses[id]
85                        msg = NSCAMessage(id)
86                        self._responses[id] = msg
87                        return msg
88
89        def set_response(self, msg):
90                with sync:
91                        self._responses[msg.uuid].copy_changed_attributes(msg)
92
93        def del_response(self, id):
94                with sync:
95                        del self._responses[id]
96                       
97       
98        def desc(self):
99                return 'Testcase for NSCA protocol'
100
101        def title(self):
102                return 'NSCA Server test'
103
104        def setup(self, plugin_id, prefix):
105                self.key = '_%stest_command'%prefix
106                self.reg = Registry.get(plugin_id)
107                self.reg.simple_subscription('nsca_test_inbox', NSCAServerTest.simple_inbox_handler)
108                self.reg.subscription('nsca_test_inbox', NSCAServerTest.inbox_handler)
109
110        def simple_inbox_handler(channel, source, command, code, message, perf):
111                instance = NSCAServerTest.getInstance()
112                return instance.simple_inbox_handler_wrapped(channel, source, command, code, message, perf)
113        simple_inbox_handler = Callable(simple_inbox_handler)
114
115        def inbox_handler(channel, request):
116                instance = NSCAServerTest.getInstance()
117                return instance.inbox_handler_wrapped(channel, request)
118        inbox_handler = Callable(inbox_handler)
119       
120        def simple_inbox_handler_wrapped(self, channel, source, command, status, message, perf):
121                log('Got simple message %s on %s'%(command, channel))
122                msg = self.get_response(command)
123                msg.source = source
124                msg.status = status
125                msg.message = message
126                msg.perfdata = perf
127                msg.got_simple_response = True
128                self.set_response(msg)
129                return True
130
131        def inbox_handler_wrapped(self, channel, request):
132                message = plugin_pb2.SubmitRequestMessage()
133                message.ParseFromString(request)
134                command = message.payload[0].command
135                log('Got message %s on %s'%(command, channel))
136               
137                msg = self.get_response(command)
138                msg.got_response = True
139                self.set_response(msg)
140                return None
141               
142        def teardown(self):
143                None
144               
145        def wait_and_validate(self, uuid, result, msg, perf, tag):
146                found = False
147                for i in range(0,10):
148                        if self.has_response(uuid):
149                                rmsg = self.get_response(uuid)
150                                result.add_message(rmsg.got_response, 'Testing to recieve message using %s'%tag)
151                                if 'exec' in tag and 'UNKNOWN' in tag and not rmsg.got_simple_response:
152                                        result.add_message(True, 'FAILED -- TODO -- FIX ME -- Testing to recieve simple message using %s'%tag)
153                                else:
154                                        result.add_message(rmsg.got_simple_response, 'Testing to recieve simple message using %s'%tag)
155                                #result.assert_equals(rmsg.last_source, source, 'Verify that source is sent through')
156                                result.assert_equals(rmsg.command, uuid, 'Verify that command is sent through using %s'%tag)
157                                result.assert_contains(rmsg.message, msg, 'Verify that message is sent through using %s'%tag)
158                                result.assert_equals(rmsg.perfdata, perf, 'Verify that performance data is sent through using %s'%tag)
159                                self.del_response(uuid)
160                                return True
161                        else:
162                                log('Waiting for %s (%d/10)'%(uuid, i+1))
163                                sleep(1)
164                result.add_message(False, 'Failed to recieve message %s using %s'%(uuid, tag))
165                return False
166       
167               
168        def submit_payload(self, encryption, source, status, msg, perf, tag):
169                message = plugin_pb2.SubmitRequestMessage()
170               
171                message.header.version = plugin_pb2.Common.VERSION_1
172                message.header.recipient_id = "test_rp"
173                message.channel = 'nsca_test_outbox'
174                host = message.header.hosts.add()
175                host.address = "127.0.0.1:15667"
176                host.id = "test_rp"
177                enc = host.metadata.add()
178                enc.key = "encryption"
179                enc.value = encryption
180                enc = host.metadata.add()
181                enc.key = "password"
182                enc.value = 'pwd-%s'%encryption
183
184                uid = str(uuid.uuid4())
185                payload = message.payload.add()
186                payload.result = status
187                payload.command = uid
188                payload.message = '%s - %s'%(uid, msg)
189                payload.source = source
190                (result_code, err) = core.submit('nsca_test_outbox', message.SerializeToString())
191
192                result = TestResult('Testing payload: %s'%tag)
193                result.add_message(len(err) == 0, 'Testing to send message using %s/sbp'%tag, err)
194                self.wait_and_validate(uid, result, msg, perf, '%s/spb'%tag)
195                return result
196               
197        def submit_via_exec(self, encryption, source, status, msg, perf, tag):
198                uid = str(uuid.uuid4())
199       
200                args = [
201                        #'--exec', 'submit',
202                        '--alias', uid,
203                        '--result', '%d'%status,
204                        '--message', '%s - %s'%(uid, msg),
205                        '--encryption', encryption,
206                        '--password', 'pwd-%s'%encryption,
207                        '--host', '127.0.0.1:15667'
208                        ]
209                (result_code, result_message) = core.simple_exec('any', 'nsca_submit', args)
210                result = TestResult()
211               
212                result.add_message(result_code == 0, 'Testing to send message using %s/exec:1'%tag)
213                result.add_message(len(result_message) == 1, 'Testing to send message using %s/exec:2'%tag, len(result_message))
214                result.add_message(len(result_message[0]) == 0, 'Testing to send message using %s/exec:3'%tag, result_message[0])
215                self.wait_and_validate(uid, result, msg, perf, '%s/exec'%tag)
216                return result
217
218        def test_one_crypto_full(self, encryption, state, key):
219                result = TestResult('Testing %s/%s'%(encryption, key))
220                result.add(self.submit_payload(encryption, '%ssrc%s'%(key, key), state, '%smsg%s'%(key, key), '', '%s/%s'%(state, encryption)))
221                result.add(self.submit_via_exec(encryption, '%ssrc%s'%(key, key), state, '%smsg%s'%(key, key), '', '%s/%s'%(state, encryption)))
222                return result
223
224        def test_one_crypto(self, crypto):
225                conf = Settings.get()
226                conf.set_string('/settings/NSCA/test_nsca_server', 'encryption', '%s'%crypto)
227                conf.set_string('/settings/NSCA/test_nsca_server', 'password', 'pwd-%s'%crypto)
228                core.reload('test_nsca_server')
229                result = TestResult('Testing encryption algorith: %s'%crypto)
230                result.add_message(isOpen('localhost', 15667), 'Checking that port is open')
231                result.add(self.test_one_crypto_full(crypto, status.UNKNOWN, 'unknown'))
232                result.add(self.test_one_crypto_full(crypto, status.OK, 'ok'))
233                result.add(self.test_one_crypto_full(crypto, status.WARNING, 'warn'))
234                result.add(self.test_one_crypto_full(crypto, status.CRITICAL, 'crit'))
235                return result
236
237        def run_test(self):
238                result = TestResult()
239                cryptos = ["none", "xor", "des", "3des", "cast128", "xtea", "blowfish", "twofish", "rc2", "aes", "aes256", "aes192", "aes128", "serpent", "gost", "3way"]
240                for c in cryptos:
241                        result.add_message(True, 'Testing crypto: %s'%c)
242                        result.add(self.test_one_crypto(c))
243               
244                return result
245               
246        def install(self, arguments):
247                conf = Settings.get()
248                conf.set_string('/modules', 'test_nsca_server', 'NSCAServer')
249                conf.set_string('/modules', 'test_nsca_client', 'NSCAClient')
250                conf.set_string('/modules', 'pytest', 'PythonScript')
251
252                conf.set_string('/settings/pytest/scripts', 'test_nsca', 'test_nsca.py')
253               
254                conf.set_string('/settings/NSCA/test_nsca_server', 'port', '15667')
255                conf.set_string('/settings/NSCA/test_nsca_server', 'inbox', 'nsca_test_inbox')
256                conf.set_string('/settings/NSCA/test_nsca_server', 'encryption', '1')
257
258                conf.set_string('/settings/NSCA/test_nsca_client/targets', 'nsca_test_local', 'nsca://127.0.0.1:15667')
259                conf.set_string('/settings/NSCA/test_nsca_client', 'channel', 'nsca_test_outbox')
260               
261                conf.save()
262
263        def uninstall(self):
264                None
265
266        def help(self):
267                None
268
269        def init(self, plugin_id):
270                None
271
272        def shutdown(self):
273                None
274               
275        def require_boot(self):
276                return True
277               
278
279setup_singleton(NSCAServerTest)
280
281all_tests = [NSCAServerTest]
282
283def __main__():
284        install_testcases(all_tests)
285       
286def init(plugin_id, plugin_alias, script_alias):
287        init_testcases(plugin_id, plugin_alias, script_alias, all_tests)
288
289def shutdown():
290        shutdown_testcases()
Note: See TracBrowser for help on using the repository browser.