test_utils.py 8.09 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
Utilities and mock modules for unittests of statistics modules

"""
import os
import io
import time
import sys
import threading
import tempfile

import msgq
import isc.config.cfgmgr 
import stats
import stats_httpd

# TODO: consider appropriate timeout seconds
TIMEOUT_SEC = 0.01

def send_command(command_name, module_name, params=None, session=None, nonblock=False, timeout=TIMEOUT_SEC*2):
    if not session:
        cc_session = isc.cc.Session()
    else:
        cc_session = session
    orig_timeout = cc_session.get_timeout()
    cc_session.set_timeout(timeout * 1000)
    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:
        if not session:
            cc_session.close()
        else:
            cc_session.set_timeout(orig_timeout)

def send_shutdown(module_name):
    return send_command("shutdown", module_name)

class ThreadingServerManager:
45
    def __init__(self, server_class):
46
47
        self.server_class = server_class
        self.server_class_name = server_class.__name__
48
        self.server = self.server_class()
49
50
51
52
53
54
55
56
57
58
59
60
61
        self.server._thread = threading.Thread(
            name=self.server_class_name, target=self.server.run)
        self.server._thread.daemon = True
        
    def run(self):
        self.server._thread.start()
        self.server._started.wait()

    def shutdown(self):
        self.server.shutdown()
        self.server._thread.join(TIMEOUT_SEC)

class MockMsgq:
62
    def __init__(self):
63
        self._started = threading.Event()
64
        self.msgq = msgq.MsgQ(None)
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
        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
        finally:
            self.shutdown()

    def shutdown(self):
        self.msgq.shutdown()

class MockCfgmgr:
82
    def __init__(self):
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
        self._started = threading.Event()
        self.cfgmgr = isc.config.cfgmgr.ConfigManager(
            os.environ['CONFIG_TESTDATA_PATH'], "b10-config.db")
        self.cfgmgr.read_config()

    def run(self):
        self._started.set()
        try:
            self.cfgmgr.run()
        finally:
            self.shutdown()

    def shutdown(self):
        self.cfgmgr.running = False
            
class MockBoss:
    spec_str = """\
{
  "module_spec": {
    "module_name": "Boss",
    "module_description": "Mock Master process",
    "config_data": [],
    "commands": [
      {
        "command_name": "sendstats",
        "command_description": "Send data to a statistics module at once",
        "command_args": []
      }
    ],
    "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)

128
    def __init__(self):
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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
        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 = ''

    def run(self):
        self.mccs.start()
        self.running = True
        self._started.set()
        while self.running:
            self.mccs.check_command(False)

    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
        if command == 'sendstats':
            params = { "owner": "Boss",
                       "data": {
                    'boot_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', self._BASETIME)
                    } 
                       }
            return send_command("set", "Stats", params=params, session=self.cc_session)
        return isc.config.create_answer(1, "Unknown Command")

class MockAuth:
    spec_str = """\
{
  "module_spec": {
    "module_name": "Auth",
    "module_description": "Mock Authoritative service",
    "config_data": [],
    "commands": [
      {
        "command_name": "sendstats",
        "command_description": "Send data to a statistics module at once",
        "command_args": []
      }
    ],
    "statistics": [
      {
        "item_name": "queries.tcp",
        "item_type": "integer",
        "item_optional": false,
        "item_default": 0,
185
        "item_title": "Queries TCP",
186
187
188
189
190
191
192
193
194
195
196
197
198
199
        "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"
      }
    ]
  }
}
"""
200
    def __init__(self):
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
        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

    def run(self):
        self.mccs.start()
        self.running = True
        self._started.set()
        while self.running:
            self.mccs.check_command(False)

    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
        if command == 'sendstats':
            params = { "owner": "Auth",
                       "data": { 'queries.tcp': self.queries_tcp,
                                 'queries.udp': self.queries_udp } }
            return send_command("set", "Stats", params=params, session=self.cc_session)
        return isc.config.create_answer(1, "Unknown Command")

class MyStats(stats.Stats):
238
    def __init__(self):
239
        self._started = threading.Event()
240
        stats.Stats.__init__(self)
241
242
243
244
245
246
247
248
249

    def run(self):
        self._started.set()
        stats.Stats.start(self)

    def shutdown(self):
        send_shutdown("Stats")

class MyStatsHttpd(stats_httpd.StatsHttpd):
250
    def __init__(self):
251
        self._started = threading.Event()
252
        stats_httpd.StatsHttpd.__init__(self)
253
254
255
256
257
258
259
260
261

    def run(self):
        self._started.set()
        stats_httpd.StatsHttpd.start(self)

    def shutdown(self):
        send_shutdown("StatsHttpd")

class BaseModules:
262
    def __init__(self):
263
264
265
266
267
        self.class_name = BaseModules.__name__

        # Change value of BIND10_MSGQ_SOCKET_FILE in environment variables
        os.environ['BIND10_MSGQ_SOCKET_FILE'] = tempfile.mktemp(prefix='unix_socket.')
        # MockMsgq
268
        self.msgq = ThreadingServerManager(MockMsgq)
269
270
        self.msgq.run()
        # MockCfgmgr
271
        self.cfgmgr = ThreadingServerManager(MockCfgmgr)
272
273
        self.cfgmgr.run()
        # MockBoss
274
        self.boss = ThreadingServerManager(MockBoss)
275
276
        self.boss.run()
        # MockAuth
277
        self.auth = ThreadingServerManager(MockAuth)
278
279
280
281
282
283
284
285
286
287
288
        self.auth.run()

    def shutdown(self):
        # MockAuth
        self.auth.shutdown()
        # MockBoss
        self.boss.shutdown()
        # MockCfgmgr
        self.cfgmgr.shutdown()
        # MockMsgq
        self.msgq.shutdown()