test_utils.py 15.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
"""
Utilities and mock modules for unittests of statistics modules

"""
import os
import io
import time
import sys
import threading
import tempfile
Naoki Kambe's avatar
Naoki Kambe committed
11
import json
12
import signal
13
14

import msgq
15
import isc.config.cfgmgr
16
17
18
import stats
import stats_httpd

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class SignalHandler():
    """A signal handler class for deadlock in unittest"""
    def __init__(self, fail_handler, timeout=20):
        """sets a schedule in SIGARM for invoking the handler via
        unittest.TestCase after timeout seconds (default is 20)"""
        self.fail_handler = fail_handler
        self.orig_handler = signal.signal(signal.SIGALRM, self.sig_handler)
        signal.alarm(timeout)

    def reset(self):
        """resets the schedule in SIGALRM"""
        signal.alarm(0)
        signal.signal(signal.SIGALRM, self.orig_handler)

    def sig_handler(self, signal, frame):
        """envokes unittest.TestCase.fail as a signal handler"""
        self.fail_handler("A deadlock might be detected")

Naoki Kambe's avatar
Naoki Kambe committed
37
38
def send_command(command_name, module_name, params=None, session=None, nonblock=False, timeout=None):
    if session is not None:
39
        cc_session = session
Naoki Kambe's avatar
Naoki Kambe committed
40
41
42
43
44
    else:
        cc_session = isc.cc.Session()
    if timeout is not None:
        orig_timeout = cc_session.get_timeout()
        cc_session.set_timeout(timeout * 1000)
45
46
47
48
49
50
51
52
53
    command = isc.config.ccsession.create_command(command_name, params)
    seq = cc_session.group_sendmsg(command, module_name)
    try:
        (answer, env) = cc_session.group_recvmsg(nonblock, seq)
        if answer:
            return isc.config.ccsession.parse_answer(answer)
    except isc.cc.SessionTimeout:
        pass
    finally:
Naoki Kambe's avatar
Naoki Kambe committed
54
        if timeout is not None:
55
            cc_session.set_timeout(orig_timeout)
Naoki Kambe's avatar
Naoki Kambe committed
56
57
        if session is None:
            cc_session.close()
58

Naoki Kambe's avatar
Naoki Kambe committed
59
60
def send_shutdown(module_name, **kwargs):
    return send_command("shutdown", module_name, **kwargs)
61
62

class ThreadingServerManager:
Naoki Kambe's avatar
Naoki Kambe committed
63
    def __init__(self, server, *args, **kwargs):
64
        self.server = server(*args, **kwargs)
Naoki Kambe's avatar
Naoki Kambe committed
65
        self.server_name = server.__name__
66
        self.server._thread = threading.Thread(
Naoki Kambe's avatar
Naoki Kambe committed
67
            name=self.server_name, target=self.server.run)
68
        self.server._thread.daemon = True
69

70
71
72
    def run(self):
        self.server._thread.start()
        self.server._started.wait()
73
        self.server._started.clear()
74

75
76
77
78
79
80
81
82
    def shutdown(self, blocking=False):
        """Shut down the server by calling its own shutdown() method.
           Then wait for its thread to finish. If blocking is True,
           the thread.join() blocks until the thread finishes. If not,
           it uses a zero timeout. The latter is necessary in a number
           of existing tests. We should redo this part (we should not
           even need threads in most, if not all, of these threads, see
           ticket #1668)"""
83
        self.server.shutdown()
84
85
86
87
        if blocking:
            self.server._thread.join()
        else:
            self.server._thread.join(0) # timeout is 0
88

Naoki Kambe's avatar
Naoki Kambe committed
89
90
91
92
93
94
95
96
def do_nothing(*args, **kwargs): pass

class dummy_sys:
    """Dummy for sys"""
    class dummy_io:
        write = do_nothing
    stdout = stderr = dummy_io()

97
class MockMsgq:
98
    def __init__(self):
99
        self._started = threading.Event()
Naoki Kambe's avatar
Naoki Kambe committed
100
101
102
103
        # suppress output to stdout and stderr
        msgq.sys = dummy_sys()
        msgq.print = do_nothing
        self.msgq = msgq.MsgQ(verbose=False)
104
105
106
107
108
109
110
111
112
113
        result = self.msgq.setup()
        if result:
            sys.exit("Error on Msgq startup: %s" % result)

    def run(self):
        self._started.set()
        try:
            self.msgq.run()
        except Exception:
            pass
114
115
116
117
118
        finally:
            # explicitly shut down the socket of the msgq before
            # shutting down the msgq
            self.msgq.listen_socket.shutdown(msgq.socket.SHUT_RDWR)
            self.msgq.shutdown()
119
120

    def shutdown(self):
Naoki Kambe's avatar
Naoki Kambe committed
121
        # do nothing
Naoki Kambe's avatar
Naoki Kambe committed
122
        pass
123
124

class MockCfgmgr:
125
    def __init__(self):
126
127
        self._started = threading.Event()
        self.cfgmgr = isc.config.cfgmgr.ConfigManager(
128
            os.environ['CONFIG_TESTDATA_PATH'], "b10-config_test.db")
129
130
131
132
        self.cfgmgr.read_config()

    def run(self):
        self._started.set()
Naoki Kambe's avatar
Naoki Kambe committed
133
134
135
136
        try:
            self.cfgmgr.run()
        except Exception:
            pass
137
138
139

    def shutdown(self):
        self.cfgmgr.running = False
140

141
142
143
144
145
146
class MockBoss:
    spec_str = """\
{
  "module_spec": {
    "module_name": "Boss",
    "module_description": "Mock Master process",
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    "config_data": [
      {
        "item_name": "components",
        "item_type": "named_set",
        "item_optional": false,
        "item_default": {
          "b10-stats": { "address": "Stats", "kind": "dispensable" },
          "b10-cmdctl": { "special": "cmdctl", "kind": "needed" }
        },
        "named_set_item_spec": {
          "item_name": "component",
          "item_type": "map",
          "item_optional": false,
          "item_default": { },
          "map_item_spec": [
            {
              "item_name": "special",
              "item_optional": true,
              "item_type": "string"
            },
            {
              "item_name": "process",
              "item_optional": true,
              "item_type": "string"
            },
            {
              "item_name": "kind",
              "item_optional": false,
              "item_type": "string",
              "item_default": "dispensable"
            },
            {
              "item_name": "address",
              "item_optional": true,
              "item_type": "string"
            },
            {
              "item_name": "params",
              "item_optional": true,
              "item_type": "list",
              "list_item_spec": {
                "item_name": "param",
                "item_optional": false,
                "item_type": "string",
                "item_default": ""
              }
            },
            {
              "item_name": "priority",
              "item_optional": true,
              "item_type": "integer"
            }
          ]
        }
      }
    ],
203
    "commands": [
204
205
206
207
208
209
210
211
212
213
      {
        "command_name": "shutdown",
        "command_description": "Shut down BIND 10",
        "command_args": []
      },
      {
        "command_name": "ping",
        "command_description": "Ping the boss process",
        "command_args": []
      },
214
215
216
217
      {
        "command_name": "show_processes",
        "command_description": "List the running BIND 10 processes",
        "command_args": []
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
      }
    ],
    "statistics": [
      {
        "item_name": "boot_time",
        "item_type": "string",
        "item_optional": false,
        "item_default": "1970-01-01T00:00:00Z",
        "item_title": "Boot time",
        "item_description": "A date time when bind10 process starts initially",
        "item_format": "date-time"
      }
    ]
  }
}
"""
    _BASETIME = (2011, 6, 22, 8, 14, 8, 2, 173, 0)

236
    def __init__(self):
237
238
239
240
241
242
243
244
245
246
247
        self._started = threading.Event()
        self.running = False
        self.spec_file = io.StringIO(self.spec_str)
        # create ModuleCCSession object
        self.mccs = isc.config.ModuleCCSession(
            self.spec_file,
            self.config_handler,
            self.command_handler)
        self.spec_file.close()
        self.cc_session = self.mccs._session
        self.got_command_name = ''
248
249
250
251
        self.pid_list = [[ 9999, "b10-auth"   ],
                         [ 9998, "b10-auth-2" ],
                         [ 9997, "b10-auth-3" ],
                         [ 9996, "b10-auth-4" ]]
252
253
254
255
256

    def run(self):
        self.mccs.start()
        self.running = True
        self._started.set()
Naoki Kambe's avatar
Naoki Kambe committed
257
258
259
260
261
        try:
            while self.running:
                self.mccs.check_command(False)
        except Exception:
            pass
262
263
264
265
266
267
268
269

    def shutdown(self):
        self.running = False

    def config_handler(self, new_config):
        return isc.config.create_answer(0)

    def command_handler(self, command, *args, **kwargs):
Naoki Kambe's avatar
Naoki Kambe committed
270
        self._started.set()
271
        self.got_command_name = command
272
273
274
        sdata = {
            'boot_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', self._BASETIME)
            }
275
        params = { "owner": "Boss",
276
                   "data": sdata
277
                   }
278
        if command == 'getstats':
279
280
281
282
283
            notfound = [ t for t in args[0]['trees'] if t not in sdata ]
            if notfound:
                return isc.config.create_answer(1, notfound)
            return isc.config.create_answer(
                0, dict([(t,sdata[t]) for t in args[0]['trees'] if t in sdata ]))
284
285
286
        elif command == 'show_processes':
            # Return dummy pids
            return isc.config.create_answer(
287
                0, self.pid_list)
288
289
290
291
292
293
294
295
296
        return isc.config.create_answer(1, "Unknown Command")

class MockAuth:
    spec_str = """\
{
  "module_spec": {
    "module_name": "Auth",
    "module_description": "Mock Authoritative service",
    "config_data": [],
297
    "commands": [],
298
299
300
301
302
303
    "statistics": [
      {
        "item_name": "queries.tcp",
        "item_type": "integer",
        "item_optional": false,
        "item_default": 0,
304
        "item_title": "Queries TCP",
305
306
307
308
309
310
311
312
313
        "item_description": "A number of total query counts which all auth servers receive over TCP since they started initially"
      },
      {
        "item_name": "queries.udp",
        "item_type": "integer",
        "item_optional": false,
        "item_default": 0,
        "item_title": "Queries UDP",
        "item_description": "A number of total query counts which all auth servers receive over UDP since they started initially"
314
315
      },
      {
316
        "item_name": "queries.perzone",
317
318
        "item_type": "list",
        "item_optional": false,
319
320
321
322
323
324
325
326
327
328
329
330
        "item_default": [
          {
            "zonename" : "test1.example",
            "queries.udp" : 1,
            "queries.tcp" : 2
          },
          {
            "zonename" : "test2.example",
            "queries.udp" : 3,
            "queries.tcp" : 4
          }
        ],
331
332
333
        "item_title": "Queries per zone",
        "item_description": "Queries per zone",
        "list_item_spec": {
334
          "item_name": "zones",
335
336
337
338
339
340
341
342
          "item_type": "map",
          "item_optional": false,
          "item_default": {},
          "map_item_spec": [
            {
              "item_name": "zonename",
              "item_type": "string",
              "item_optional": false,
Naoki Kambe's avatar
Naoki Kambe committed
343
344
345
              "item_default": "",
              "item_title": "Zonename",
              "item_description": "Zonename"
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
            },
            {
              "item_name": "queries.udp",
              "item_type": "integer",
              "item_optional": false,
              "item_default": 0,
              "item_title": "Queries UDP per zone",
              "item_description": "A number of UDP query counts per zone"
            },
            {
              "item_name": "queries.tcp",
              "item_type": "integer",
              "item_optional": false,
              "item_default": 0,
              "item_title": "Queries TCP per zone",
              "item_description": "A number of TCP query counts per zone"
            }
          ]
        }
365
366
367
368
369
      }
    ]
  }
}
"""
370
    def __init__(self):
371
372
373
374
375
376
377
378
379
380
381
382
383
        self._started = threading.Event()
        self.running = False
        self.spec_file = io.StringIO(self.spec_str)
        # create ModuleCCSession object
        self.mccs = isc.config.ModuleCCSession(
            self.spec_file,
            self.config_handler,
            self.command_handler)
        self.spec_file.close()
        self.cc_session = self.mccs._session
        self.got_command_name = ''
        self.queries_tcp = 3
        self.queries_udp = 2
384
        self.queries_per_zone = [{
385
                'zonename': 'test1.example',
386
387
388
                'queries.tcp': 5,
                'queries.udp': 4
                }]
389
390
391
392
393

    def run(self):
        self.mccs.start()
        self.running = True
        self._started.set()
Naoki Kambe's avatar
Naoki Kambe committed
394
395
396
397
398
        try:
            while self.running:
                self.mccs.check_command(False)
        except Exception:
            pass
399
400
401
402
403
404
405
406
407

    def shutdown(self):
        self.running = False

    def config_handler(self, new_config):
        return isc.config.create_answer(0)

    def command_handler(self, command, *args, **kwargs):
        self.got_command_name = command
408
409
410
        sdata = { 'queries.tcp': self.queries_tcp,
                       'queries.udp': self.queries_udp,
                       'queries.perzone' : self.queries_per_zone }
411
        if command == 'getstats':
412
413
414
415
416
            notfound = [ t for t in args[0]['trees'] if t not in sdata ]
            if notfound:
                return isc.config.create_answer(1, notfound)
            return isc.config.create_answer(
                0, dict([(t,sdata[t]) for t in args[0]['trees'] if t in sdata ]))
417
418
419
        return isc.config.create_answer(1, "Unknown Command")

class MyStats(stats.Stats):
420
    def __init__(self):
421
        self._started = threading.Event()
422
        stats.Stats.__init__(self)
423
424
425

    def run(self):
        self._started.set()
Naoki Kambe's avatar
Naoki Kambe committed
426
427
428
        try:
            self.start()
        except Exception:
429
            raise
430
431

    def shutdown(self):
Naoki Kambe's avatar
Naoki Kambe committed
432
        self.command_shutdown()
433
434

class MyStatsHttpd(stats_httpd.StatsHttpd):
Naoki Kambe's avatar
Naoki Kambe committed
435
436
    ORIG_SPECFILE_LOCATION = stats_httpd.SPECFILE_LOCATION
    def __init__(self, *server_address):
437
        self._started = threading.Event()
Naoki Kambe's avatar
Naoki Kambe committed
438
        if server_address:
439
            stats_httpd.SPECFILE_LOCATION = self.create_specfile(*server_address)
Naoki Kambe's avatar
Naoki Kambe committed
440
441
442
            try:
                stats_httpd.StatsHttpd.__init__(self)
            finally:
443
444
                if hasattr(stats_httpd.SPECFILE_LOCATION, "close"):
                    stats_httpd.SPECFILE_LOCATION.close()
Naoki Kambe's avatar
Naoki Kambe committed
445
446
447
448
                stats_httpd.SPECFILE_LOCATION = self.ORIG_SPECFILE_LOCATION
        else:
            stats_httpd.StatsHttpd.__init__(self)

449
450
451
452
453
454
455
456
457
458
459
460
461
462
    def create_specfile(self, *server_address):
        spec_io = open(self.ORIG_SPECFILE_LOCATION)
        try:
            spec = json.load(spec_io)
            spec_io.close()
            config = spec['module_spec']['config_data']
            for i in range(len(config)):
                if config[i]['item_name'] == 'listen_on':
                    config[i]['item_default'] = \
                        [ dict(address=a[0], port=a[1]) for a in server_address ]
                    break
            return io.StringIO(json.dumps(spec))
        finally:
            spec_io.close()
463
464
465

    def run(self):
        self._started.set()
Naoki Kambe's avatar
Naoki Kambe committed
466
467
468
469
        try:
            self.start()
        except Exception:
            pass
470
471

    def shutdown(self):
Naoki Kambe's avatar
Naoki Kambe committed
472
        self.command_handler('shutdown', None)
473
474

class BaseModules:
475
    def __init__(self):
476
        # MockMsgq
477
        self.msgq = ThreadingServerManager(MockMsgq)
478
        self.msgq.run()
Naoki Kambe's avatar
Naoki Kambe committed
479
480
        # Check whether msgq is ready. A SessionTimeout is raised here if not.
        isc.cc.session.Session().close()
481
        # MockCfgmgr
482
        self.cfgmgr = ThreadingServerManager(MockCfgmgr)
483
484
        self.cfgmgr.run()
        # MockBoss
485
        self.boss = ThreadingServerManager(MockBoss)
486
        self.boss.run()
487
        # MockAuth * 4
Naoki Kambe's avatar
Naoki Kambe committed
488
489
490
491
        for i in ['', '2', '3', '4']:
            setattr(self,"auth"+i, \
                        ThreadingServerManager(MockAuth))
            getattr(self, "auth"+i).run()
492
493
494
495
496
497
498
499
500
501

    def shutdown(self):
        # MockAuth
        self.auth.shutdown()
        # MockBoss
        self.boss.shutdown()
        # MockCfgmgr
        self.cfgmgr.shutdown()
        # MockMsgq
        self.msgq.shutdown()
Naoki Kambe's avatar
Naoki Kambe committed
502
503
504
505
506
507
508
        # remove the unused socket file
        socket_file = self.msgq.server.msgq.socket_file
        try:
            if os.path.exists(socket_file):
                os.remove(socket_file)
        except OSError:
            pass