summaryrefslogtreecommitdiff
path: root/qpid/extras/qmf/src/py/qmf2-prototype/tests/async_query.py
blob: b1c01611f7f2f65aedaadefb2ac663b6869881ca (plain)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
128
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
import unittest
import logging
from threading import Thread, Event

import qpid.messaging
from qmf2.common import (Notifier, SchemaObjectClass, SchemaClassId,
                           SchemaProperty, qmfTypes, SchemaMethod, QmfQuery,
                           QmfData, WorkItem)
import qmf2.console
from qmf2.agent import(QmfAgentData, Agent)


class _testNotifier(Notifier):
    def __init__(self):
        self._event = Event()

    def indication(self):
        # note: called by qmf daemon thread
        self._event.set()

    def wait_for_work(self, timeout):
        # note: called by application thread to wait
        # for qmf to generate work
        self._event.wait(timeout)
        timed_out = self._event.isSet() == False
        if not timed_out:
            self._event.clear()
            return True
        return False


class _agentApp(Thread):
    def __init__(self, name, broker_url, heartbeat):
        Thread.__init__(self)
        self.notifier = _testNotifier()
        self.broker_url = broker_url
        self.agent = Agent(name,
                           _notifier=self.notifier,
                           heartbeat_interval=heartbeat)

        # Dynamically construct a management database

        _schema = SchemaObjectClass( _classId=SchemaClassId("MyPackage", "MyClass"),
                                     _desc="A test data schema",
                                     _object_id_names=["index1", "index2"] )
        # add properties
        _schema.add_property( "index1", SchemaProperty(qmfTypes.TYPE_UINT8))
        _schema.add_property( "index2", SchemaProperty(qmfTypes.TYPE_LSTR))

        # these two properties are statistics
        _schema.add_property( "query_count", SchemaProperty(qmfTypes.TYPE_UINT32))
        _schema.add_property( "method_call_count", SchemaProperty(qmfTypes.TYPE_UINT32))

        # These two properties can be set via the method call
        _schema.add_property( "set_string", SchemaProperty(qmfTypes.TYPE_LSTR))
        _schema.add_property( "set_int", SchemaProperty(qmfTypes.TYPE_UINT32))

        # add method
        _meth = SchemaMethod( _desc="Method to set string and int in object." )
        _meth.add_argument( "arg_int", SchemaProperty(qmfTypes.TYPE_UINT32) )
        _meth.add_argument( "arg_str", SchemaProperty(qmfTypes.TYPE_LSTR) )
        _schema.add_method( "set_meth", _meth )

        # Add schema to Agent

        self.agent.register_object_class(_schema)

        # instantiate managed data objects matching the schema

        _obj1 = QmfAgentData( self.agent, _schema=_schema,
                              _values={"index1":100, "index2":"a name"})
        _obj1.set_value("set_string", "UNSET")
        _obj1.set_value("set_int", 0)
        _obj1.set_value("query_count", 0)
        _obj1.set_value("method_call_count", 0)
        self.agent.add_object( _obj1 )

        self.agent.add_object( QmfAgentData( self.agent, _schema=_schema,
                                             _values={"index1":99,
                                                      "index2": "another name",
                                                      "set_string": "UNSET",
                                                      "set_int": 0,
                                                      "query_count": 0,
                                                      "method_call_count": 0} ))

        self.agent.add_object( QmfAgentData( self.agent, _schema=_schema,
                                             _values={"index1":50,
                                                      "index2": "my name",
                                                      "set_string": "SET",
                                                      "set_int": 0,
                                                      "query_count": 0,
                                                      "method_call_count": 0} ))


        # add an "unstructured" object to the Agent
        _obj2 = QmfAgentData(self.agent, _object_id="01545")
        _obj2.set_value("field1", "a value")
        _obj2.set_value("field2", 2)
        _obj2.set_value("field3", {"a":1, "map":2, "value":3})
        _obj2.set_value("field4", ["a", "list", "value"])
        _obj2.set_value("index1", 50)
        self.agent.add_object(_obj2)

        _obj2 = QmfAgentData(self.agent, _object_id="01546")
        _obj2.set_value("field1", "a value")
        _obj2.set_value("field2", 3)
        _obj2.set_value("field3", {"a":1, "map":2, "value":3})
        _obj2.set_value("field4", ["a", "list", "value"])
        _obj2.set_value("index1", 51)
        self.agent.add_object(_obj2)

        _obj2 = QmfAgentData(self.agent, _object_id="01544")
        _obj2.set_value("field1", "a value")
        _obj2.set_value("field2", 4)
        _obj2.set_value("field3", {"a":1, "map":2, "value":3})
        _obj2.set_value("field4", ["a", "list", "value"])
        _obj2.set_value("index1", 49)
        self.agent.add_object(_obj2)

        _obj2 = QmfAgentData(self.agent, _object_id="01543")
        _obj2.set_value("field1", "a value")
        _obj2.set_value("field2", 4)
        _obj2.set_value("field3", {"a":1, "map":2, "value":3})
        _obj2.set_value("field4", ["a", "list", "value"])
        _obj2.set_value("index1", 48)
        self.agent.add_object(_obj2)

        self.running = False
        self.ready = Event()

    def start_app(self):
        self.running = True
        self.start()
        self.ready.wait(10)
        if not self.ready.is_set():
            raise Exception("Agent failed to connect to broker.")

    def stop_app(self):
        self.running = False
        # wake main thread
        self.notifier.indication() # hmmm... collide with daemon???
        self.join(10)
        if self.isAlive():
            raise Exception("AGENT DID NOT TERMINATE AS EXPECTED!!!")

    def run(self):
        # broker_url = "user/passwd@hostname:port"
        self.conn = qpid.messaging.Connection(self.broker_url)
        self.conn.open()
        self.agent.set_connection(self.conn)
        self.ready.set()

        while self.running:
            self.notifier.wait_for_work(None)
            wi = self.agent.get_next_workitem(timeout=0)
            while wi is not None:
                logging.error("UNEXPECTED AGENT WORKITEM RECEIVED=%s" % wi.get_type())
                self.agent.release_workitem(wi)
                wi = self.agent.get_next_workitem(timeout=0)

        if self.conn:
            self.agent.remove_connection(10)
        self.agent.destroy(10)




class BaseTest(unittest.TestCase):
    def configure(self, config):
        self.config = config
        self.broker = config.broker
        self.defines = self.config.defines

    def setUp(self):
        # one second agent indication interval
        self.agent_heartbeat = 1
        self.agent1 = _agentApp("agent1", self.broker, self.agent_heartbeat)
        self.agent1.start_app()
        self.agent2 = _agentApp("agent2", self.broker, self.agent_heartbeat)
        self.agent2.start_app()

    def tearDown(self):
        if self.agent1:
            self.agent1.stop_app()
            self.agent1 = None
        if self.agent2:
            self.agent2.stop_app()
            self.agent2 = None

    def test_all_schema_ids(self):
        # create console
        # find agents
        # asynchronous query for all schema ids
        self.notifier = _testNotifier()
        self.console = qmf2.console.Console(notifier=self.notifier,
                                              agent_timeout=3)
        self.conn = qpid.messaging.Connection(self.broker)
        self.conn.open()
        self.console.add_connection(self.conn)

        for aname in ["agent1", "agent2"]:
            agent = self.console.find_agent(aname, timeout=3)
            self.assertTrue(agent and agent.get_name() == aname)

            # send queries
            query = QmfQuery.create_wildcard(QmfQuery.TARGET_SCHEMA_ID)
            rc = self.console.do_query(agent, query,
                                       _reply_handle=aname)
            self.assertTrue(rc)

        # done.  Now wait for async responses

        count = 0
        while self.notifier.wait_for_work(3):
            wi = self.console.get_next_workitem(timeout=0)
            while wi is not None:
                count += 1
                self.assertTrue(wi.get_type() == WorkItem.QUERY_COMPLETE)
                self.assertTrue(wi.get_handle() == "agent1" or
                                wi.get_handle() == "agent2")
                reply = wi.get_params()
                self.assertTrue(len(reply) == 1)
                self.assertTrue(isinstance(reply[0], SchemaClassId))
                self.assertTrue(reply[0].get_package_name() == "MyPackage")
                self.assertTrue(reply[0].get_class_name() == "MyClass")
                self.console.release_workitem(wi)
                wi = self.console.get_next_workitem(timeout=0)

        self.assertTrue(count == 2)
        self.console.destroy(10)



    def test_undescribed_objs(self):
        # create console
        # find agents
        # asynchronous query for all non-schema objects
        self.notifier = _testNotifier()
        self.console = qmf2.console.Console(notifier=self.notifier,
                                              agent_timeout=3)
        self.conn = qpid.messaging.Connection(self.broker)
        self.conn.open()
        self.console.add_connection(self.conn)

        for aname in ["agent1", "agent2"]:
            agent = self.console.find_agent(aname, timeout=3)
            self.assertTrue(agent and agent.get_name() == aname)

            # send queries
            query = QmfQuery.create_wildcard(QmfQuery.TARGET_OBJECT)
            rc = self.console.do_query(agent, query, _reply_handle=aname)
            self.assertTrue(rc)

        # done.  Now wait for async responses

        count = 0
        while self.notifier.wait_for_work(3):
            wi = self.console.get_next_workitem(timeout=0)
            while wi is not None:
                count += 1
                self.assertTrue(wi.get_type() == WorkItem.QUERY_COMPLETE)
                self.assertTrue(wi.get_handle() == "agent1" or
                                wi.get_handle() == "agent2")
                reply = wi.get_params()
                self.assertTrue(len(reply) == 4)
                self.assertTrue(isinstance(reply[0], qmf2.console.QmfConsoleData))
                self.assertFalse(reply[0].is_described()) # no schema
                self.console.release_workitem(wi)
                wi = self.console.get_next_workitem(timeout=0)

        self.assertTrue(count == 2)
        self.console.destroy(10)



    def test_described_objs(self):
        # create console
        # find agents
        # asynchronous query for all schema-based objects
        self.notifier = _testNotifier()
        self.console = qmf2.console.Console(notifier=self.notifier,
                                              agent_timeout=3)
        self.conn = qpid.messaging.Connection(self.broker)
        self.conn.open()
        self.console.add_connection(self.conn)

        for aname in ["agent1", "agent2"]:
            agent = self.console.find_agent(aname, timeout=3)
            self.assertTrue(agent and agent.get_name() == aname)

            #
            t_params = {QmfData.KEY_SCHEMA_ID: SchemaClassId("MyPackage", "MyClass")}
            query = QmfQuery.create_wildcard(QmfQuery.TARGET_OBJECT, t_params)
            #
            rc = self.console.do_query(agent, query, _reply_handle=aname)
            self.assertTrue(rc)

        # done.  Now wait for async responses

        count = 0
        while self.notifier.wait_for_work(3):
            wi = self.console.get_next_workitem(timeout=0)
            while wi is not None:
                count += 1
                self.assertTrue(wi.get_type() == WorkItem.QUERY_COMPLETE)
                self.assertTrue(wi.get_handle() == "agent1" or
                                wi.get_handle() == "agent2")
                reply = wi.get_params()
                self.assertTrue(len(reply) == 3)
                self.assertTrue(isinstance(reply[0], qmf2.console.QmfConsoleData))
                self.assertTrue(reply[0].is_described()) # has schema
                self.console.release_workitem(wi)
                wi = self.console.get_next_workitem(timeout=0)

        self.assertTrue(count == 2)
        # @todo test if the console has learned the corresponding schemas....
        self.console.destroy(10)



    def test_all_schemas(self):
        # create console
        # find agents
        # asynchronous query for all schemas
        self.notifier = _testNotifier()
        self.console = qmf2.console.Console(notifier=self.notifier,
                                              agent_timeout=3)
        self.conn = qpid.messaging.Connection(self.broker)
        self.conn.open()
        self.console.add_connection(self.conn)

        # test internal state using non-api calls:
        # no schemas present yet
        self.assertTrue(len(self.console._schema_cache) == 0)
        # end test

        for aname in ["agent1", "agent2"]:
            agent = self.console.find_agent(aname, timeout=3)
            self.assertTrue(agent and agent.get_name() == aname)

            # send queries
            query = QmfQuery.create_wildcard(QmfQuery.TARGET_SCHEMA)
            rc = self.console.do_query(agent, query, _reply_handle=aname)
            self.assertTrue(rc)

        # done.  Now wait for async responses

        count = 0
        while self.notifier.wait_for_work(3):
            wi = self.console.get_next_workitem(timeout=0)
            while wi is not None:
                count += 1
                self.assertTrue(wi.get_type() == WorkItem.QUERY_COMPLETE)
                self.assertTrue(wi.get_handle() == "agent1" or
                                wi.get_handle() == "agent2")
                reply = wi.get_params()
                self.assertTrue(len(reply) == 1)
                self.assertTrue(isinstance(reply[0], qmf2.common.SchemaObjectClass))
                self.assertTrue(reply[0].get_class_id().get_package_name() == "MyPackage")
                self.assertTrue(reply[0].get_class_id().get_class_name() == "MyClass")
                self.console.release_workitem(wi)
                wi = self.console.get_next_workitem(timeout=0)

        self.assertTrue(count == 2)

        # test internal state using non-api calls:
        # schema has been learned
        self.assertTrue(len(self.console._schema_cache) == 1)
        # end test

        self.console.destroy(10)



    def test_query_expiration(self):
        # create console
        # find agents
        # kill the agents
        # send async query
        # wait for & verify expiration
        self.notifier = _testNotifier()
        self.console = qmf2.console.Console(notifier=self.notifier,
                                              agent_timeout=30)
        self.conn = qpid.messaging.Connection(self.broker)
        self.conn.open()
        self.console.add_connection(self.conn)

        # find the agents
        agents = []
        for aname in ["agent1", "agent2"]:
            agent = self.console.find_agent(aname, timeout=3)
            self.assertTrue(agent and agent.get_name() == aname)
            agents.append(agent)

        # now nuke the agents from orbit.  It's the only way to be sure.

        self.agent1.stop_app()
        self.agent1 = None
        self.agent2.stop_app()
        self.agent2 = None

        # now send queries to agents that no longer exist
        for agent in agents:
            query = QmfQuery.create_wildcard(QmfQuery.TARGET_SCHEMA)
            rc = self.console.do_query(agent, query,
                                       _reply_handle=agent.get_name(),
                                       _timeout=2)
            self.assertTrue(rc)

        # done.  Now wait for async responses due to timeouts

        count = 0
        while self.notifier.wait_for_work(3):
            wi = self.console.get_next_workitem(timeout=0)
            while wi is not None:
                count += 1
                self.assertTrue(wi.get_type() == WorkItem.QUERY_COMPLETE)
                self.assertTrue(wi.get_handle() == "agent1" or
                                wi.get_handle() == "agent2")
                reply = wi.get_params()
                self.assertTrue(len(reply) == 0)  # empty

                self.console.release_workitem(wi)
                wi = self.console.get_next_workitem(timeout=0)

        self.assertTrue(count == 2)
        self.console.destroy(10)