[svn] commit: r2584 - in /branches/trac191/src/bin/stats: stats.py.in stats.spec.pre.in stats_stub.py.in tests/b10-stats_stub_test.py tests/b10-stats_test.py

BIND 10 source code commits bind10-changes at lists.isc.org
Thu Jul 22 09:28:11 UTC 2010


Author: naokikambe
Date: Thu Jul 22 09:28:11 2010
New Revision: 2584

Log:
- make stats module fully controlled under ConfigManager
  + move "stats_data" into "config_spec" in the specfile
  + rename "command_name" in the specfile
  + some fixes related to above changes

- other some minor changes

Modified:
    branches/trac191/src/bin/stats/stats.py.in
    branches/trac191/src/bin/stats/stats.spec.pre.in
    branches/trac191/src/bin/stats/stats_stub.py.in
    branches/trac191/src/bin/stats/tests/b10-stats_stub_test.py
    branches/trac191/src/bin/stats/tests/b10-stats_test.py

Modified: branches/trac191/src/bin/stats/stats.py.in
==============================================================================
--- branches/trac191/src/bin/stats/stats.py.in (original)
+++ branches/trac191/src/bin/stats/stats.py.in Thu Jul 22 09:28:11 2010
@@ -63,9 +63,9 @@
 
     def __call__(self, *args, **kwargs):
         if args:
-            self.args=args
+            self.args = args
         if kwargs:
-            self.kwargs=kwargs
+            self.kwargs.update(kwargs)
         if self.callback:
             return self.callback(*self.args, **self.kwargs)
 
@@ -144,6 +144,7 @@
         self.verbose = verbose
         self.subject = subject
         self.session = subject.session
+        self.boot_time = get_datetime()
 
         # create ModuleCCSession object
         self.cc_session = ModuleCCSession(SPECFILE_LOCATION,
@@ -152,63 +153,81 @@
                                           self.session)
 
         # initialize internal data
-        self.stats_spec = self.get_full_spec()['stats_spec']
+        self.config_spec = self.cc_session.get_module_spec().get_config_spec()
+        self.stats_spec = self.config_spec
         self.stats_data = self.initialize_data(self.stats_spec)
 
         # add event handler invoked via SessionSubject object
+
+        # don't add 'command_' suffix to the special commands in
+        # order to prevent executing internal command via bindctl
         self.add_event(Callback('start', self.start))
         self.add_event(Callback('stop', self.stop))
         self.add_event(Callback('check', self.check))
 
+        # get commands spec
+        self.commands_spec = self.cc_session.get_module_spec().get_commands_spec()
+
         # add event handler related command_handler of ModuleCCSession
         # invoked via bindctl
-        for c in self.get_full_spec()['commands']:
-               cmd = c["command_name"]
-               try:
-                   self.add_event(Callback('command_'+cmd, eval("self.command_"+cmd)))
-               except NameError:
-                   pass
+        for cmd in self.commands_spec:
+            try:
+                # add prefix "command_"
+                name = "command_" + cmd["command_name"]
+                callback = eval("self." + name)
+                kwargs = self.initialize_data(cmd["command_args"])
+                self.add_event(Callback(name, callback, **kwargs))
+            except AttributeError as ae:
+                sys.stderr.write("[b10-stats] Caught undefined command while parsing spec file: "
+                                 +str(cmd["command_name"])+"\n")
+
+    def start(self):
+        """
+        start the cc chanel
+        """
+        # set initial value
+        self.stats_data['stats.boot_time'] = self.boot_time
+        self.stats_data['stats.start_time'] = get_datetime()
+        self.stats_data['stats.last_update_time'] = get_datetime()
+        self.stats_data['stats.lname'] = self.session.lname
+        return self.cc_session.start()
+
+    def stop(self):
+        """
+        stop the cc chanel
+        """
+        return self.cc_session.close()
+
+    def check(self):
+        """
+        check the cc chanel
+        """
+        return self.cc_session.check_command()
 
     def config_handler(self, new_config):
         """
         handle a configure from the cc channel
         """
-        # do nothing
-        return create_answer(0)
-
-    def command_handler(self, command, args):
+        if self.verbose:
+            sys.stdout.write("[b10-stats] newconfig received: "+str(new_config)+"\n")
+
+        # do nothing currently
+        return create_answer(0)
+
+    def command_handler(self, command, *args, **kwargs):
         """
         handle commands from the cc channel
         """
         cmd = None
-        # add 'command_' suffix in order to prevent executing internal
-        # command via bindctl
+        # add 'command_' suffix in order to executing command via bindctl
         name = 'command_'+command
         
         if name in self.events:
-            event=self.events[name]
-            return event(args)
+            event = self.events[name]
+            return event(*args, **kwargs)
         else:
             return self.command_unknown(command, args)
 
-    def start(self):
-        """
-        start the cc chanel
-        """
-        return self.cc_session.start()
-
-    def stop(self):
-        """
-        stop the cc chanel
-        """
-        return self.cc_session.close()
-
-    def check(self):
-        """
-        check the cc chanel
-        """
-        return self.cc_session.check_command()
-
     def command_shutdown(self, args):
         """
         handle shutdown command
@@ -218,96 +237,110 @@
         self.subject.running = False
         return create_answer(0)
 
-    def command_set(self, args):
+    def command_set(self, args, stats_data={}):
         """
         handle set command
         """
         if self.verbose:
             sys.stdout.write("[b10-stats] 'set' command received, args: "+str(args)+"\n")
 
-        data = self.stats_data
-        # Data type of the top level must be dictionary type
-        for k in args.keys():
-            data[k] = args[k]
-        self.stats_data = data
-        return create_answer(0)
-
-    def command_add(self, args):
-        """
-        handle add command
-        """
-        if self.verbose:
-            sys.stdout.write("[b10-stats] 'add' command received, args: "+str(args)+"\n")
-
-        # A internal private function adding for each element, which
+        # 'args' must be dictionary type
+        stats_data.update(args['stats_data'])
+        self.stats_data.update(stats_data)
+
+        # overwrite "stats.LastUpdateTime"
+        self.stats_data['stats.last_update_time'] = get_datetime()
+
+        return create_answer(0)
+
+    def command_increase(self, args, stats_data={}):
+        """
+        handle increase command
+        """
+        if self.verbose:
+            sys.stdout.write("[b10-stats] 'increase' command received, args: "+str(args)+"\n")
+
+        # 'args' must be dictionary type
+        stats_data.update(args['stats_data'])
+
+        # A internal private function increase for each element, which
         # is called recursively
-        def __add_data(data, args):
-            # print(type(data), type(args))
-
-            if type(data) == type([]):
+        def __increase_data(data, args):
+            if type(data) == list:
                 max = max(len(data), len(args))
                 for i in max:
                     if i in data and i in args:
-                        data[i] = __add_data(data[i], args[i])
+                        data[i] = __increase_data(data[i], args[i])
                     elif i in args:
                         data.extend(args[i:])
                         break
-            elif type(data) == type({}):
+            elif type(data) == dict:
                 for k in args.keys():
                     if k in data:
-                        data[k] = __add_data(data[k], args[k])
+                        data[k] = __increase_data(data[k], args[k])
                     else:
                         data[k] = args[k]
             else:
                 data = data + args
             return data
 
-        # call a internal function
-        self.stats_data = __add_data(self.stats_data, args)
-        return create_answer(0)
-
-    def command_del(self, args):
-        """
-        handle add command
-        """
-        if self.verbose:
-            sys.stdout.write("[b10-stats] 'del' command received, args: "+str(args)+"\n")
+        # call the internal function
+        self.stats_data = __increase_data(self.stats_data, stats_data)
+
+        # overwrite "stats.LastUpdateTime"
+        self.stats_data['stats.last_update_time'] = get_datetime()
+
+        return create_answer(0)
+
+    def command_remove(self, args, stats_item_name=''):
+        """
+        handle remove command
+        """
+        if self.verbose:
+            sys.stdout.write("[b10-stats] 'remove' command received, args: "+str(args)+"\n")
+
+        # 'args' must be dictionary type
+        if args and args['stats_item_name'] in self.stats_data:
+            stats_item_name = args['stats_item_name']
 
         # just remove one item
-        self.stats_data.pop(args)
-        return create_answer(0)
-
-    def command_spec(self, args):
-        """
-        handle show stats spec command
-        """
-        if self.verbose:
-            sys.stdout.write("[b10-stats] 'spec' command received\n")
-        return create_answer(0,dict(self.stats_spec))
-
-    def command_show(self, args):
+        self.stats_data.pop(stats_item_name)
+        return create_answer(0)
+
+    def command_show(self, args, stats_item_name=''):
         """
         handle show command
         """
         if self.verbose:
-            sys.stdout.write("[b10-stats] 'show' command received\n")
-
-        # overwrite information about stats module
+            sys.stdout.write("[b10-stats] 'show' command received, args: "+str(args)+"\n")
+
+        # always overwrite 'report_time' and 'stats.timestamp' if "show" command invoked
         self.stats_data['report_time'] = get_datetime()
         self.stats_data['stats.timestamp'] = get_timestamp()
+
+        # if with args
+        if args and args['stats_item_name'] in self.stats_data:
+            stats_item_name = args['stats_item_name']
+            return create_answer(0, {stats_item_name: self.stats_data[stats_item_name]})
+
+        return create_answer(0, self.stats_data)
+
+    def command_reset(self, args):
+        """
+        handle reset command
+        """
+        if self.verbose:
+            sys.stdout.write("[b10-stats] 'reset' command received\n")
+
+        # re-initialize internal variables
+        self.stats_data = self.initialize_data(self.stats_spec)
+
+        # reset initial value
+        self.stats_data['stats.boot_time'] = self.boot_time
+        self.stats_data['stats.start_time'] = get_datetime()
+        self.stats_data['stats.last_update_time'] = get_datetime()
         self.stats_data['stats.lname'] = self.session.lname
 
-        return create_answer(0, dict(self.stats_data))
-
-    def command_reset(self, args):
-        """
-        handle reset command
-        """
-        if self.verbose:
-            sys.stdout.write("[b10-stats] 'reset' command received\n")
-        # re-initialize data
-        self.stats_spec = self.get_full_spec()['stats_spec']
-        self.stats_data = self.initialize_data(self.stats_spec)
         return create_answer(0)
 
     def command_status(self, args):
@@ -331,30 +364,25 @@
         """
         initialize stats data
         """
-        t = spec.get('type')
-        if t == 'null':
-            return None
-        elif t == 'boolean':
-            return bool(spec.get('default', False))
-        elif t == 'string':
-            return str(spec.get('default', ''))
-        elif t in set(['number', 'integer']):
-            return int(spec.get('default', 0))
-        elif t in set(['float', 'double']):
-            return float(spec.get('default', 0.0))
-        elif t == 'array':
-            return [ self.initialize_data(x) for x in spec['items'] ]
-        elif t == 'object':
-            d = spec['properties']
-            return dict([ (k, self.initialize_data(d[k])) for k in d.keys() ])
-        else:
-            return spec.get('default')
-
-    def get_full_spec(self):
-        """
-        get full spec from cc_session
-        """
-        return self.cc_session.get_module_spec().get_full_spec()
+        def __get_init_val(spec):
+            if spec['item_type'] == 'null':
+                return None
+            elif spec['item_type'] == 'boolean':
+                return bool(spec.get('item_default', False))
+            elif spec['item_type'] == 'string':
+                return str(spec.get('item_default', ''))
+            elif spec['item_type'] in set(['number', 'integer']):
+                return int(spec.get('item_default', 0))
+            elif spec['item_type'] in set(['float', 'double', 'real']):
+                return float(spec.get('item_default', 0.0))
+            elif spec['item_type'] in set(['list', 'array']):
+                return spec.get('item_default', [ __get_init_val(spec['list_item_spec']) ])
+            elif spec['item_type'] in set(['map', 'object']):
+                return spec.get('item_default',
+                                dict([ (s['item_name'], __get_init_val(s)) for s in spec['map_item_spec'] ]) )
+            else:
+                return spec.get('item_default')
+        return dict([ (s['item_name'], __get_init_val(s)) for s in spec ])
 
 def get_timestamp():
     """
@@ -370,7 +398,7 @@
 
 def main():
     try:
-        parser=OptionParser()
+        parser = OptionParser()
         parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                       help="display more about what is going on")
         (options, args) = parser.parse_args()

Modified: branches/trac191/src/bin/stats/stats.spec.pre.in
==============================================================================
--- branches/trac191/src/bin/stats/stats.spec.pre.in (original)
+++ branches/trac191/src/bin/stats/stats.spec.pre.in Thu Jul 22 09:28:11 2010
@@ -4,92 +4,151 @@
     "module_description": "Stats daemon",
     "config_data": [
       {
-        "item_name": "dummy",
+        "item_name": "report_time",
+        "item_type": "string",
+        "item_optional": False,
+        "item_default": "1970-01-01T00:00:00Z",
+        "item_title": "Report time",
+        "item_description": "A date time when stats module reports",
+        "item_format": "date-time"
+      },
+      {
+        "item_name": "bind10.boot_time",
+        "item_type": "string",
+        "item_optional": False,
+        "item_default": "1970-01-01T00:00:00Z",
+        "item_title": "stats.BootTime",
+        "item_description": "A date time when b10-stats process starts",
+        "item_format": "date-time"
+      },
+      {
+        "item_name": "stats.boot_time",
+        "item_type": "string",
+        "item_optional": False,
+        "item_default": "1970-01-01T00:00:00Z",
+        "item_title": "stats.BootTime",
+        "item_description": "A date time when the stats module starts initially or a time when the stats module restarts",
+        "item_format": "date-time"
+      },
+      {
+        "item_name": "stats.start_time",
+        "item_type": "string",
+        "item_optional": False,
+        "item_default": "1970-01-01T00:00:00Z",
+        "item_title": "stats.StartTime",
+        "item_description": "A date time when the stats module starts collecting data and aggregating values, or resetting data at last time",
+        "item_format": "date-time"
+      },
+      {
+        "item_name": "stats.last_update_time",
+        "item_type": "string",
+        "item_optional": False,
+        "item_default": "1970-01-01T00:00:00Z",
+        "item_title": "stats.LastUpdateTime",
+        "item_description": "The latest date time when the stats module accepts from another modules like auth server or boss process and so on",
+        "item_format": "date-time"
+      },
+      {
+        "item_name": "stats.timestamp",
+        "item_type": "real",
+        "item_optional": False,
+        "item_default": 0.0,
+        "item_title": "stats.Timestamp",
+        "item_description": "Current timestamp since epoch time (1970-01-01T00:00:00Z)",
+        "item_format": "second"
+      },
+      {
+        "item_name": "stats.lname",
+        "item_type": "string",
+        "item_optional": False,
+        "item_default": "123abc at xxxx",
+        "item_title": "stats.LocalName",
+        "item_description": "A localname of stats module given via CC protocol"
+      },
+      {
+        "item_name": "auth.queries.tcp",
         "item_type": "integer",
         "item_optional": False,
-        "item_default": 1
+        "item_default": 0,
+        "item_title": "auth.queries.tcp",
+        "item_description": "A number of total query counts which all auth servers receives in TCP since they starts initially"
+      },
+      {
+        "item_name": "auth.queries.udp",
+        "item_type": "integer",
+        "item_optional": False,
+        "item_default": 0,
+        "item_title": "auth.queries.udp",
+        "item_description": "A number of total query counts which all auth servers receives in UDP since they starts initially"
       }
     ],
     "commands": [
       {
+
         "command_name": "status",
         "command_description": "status command",
         "command_args": []
       },
       {
         "command_name": "show",
-        "command_description": "Show statistics data",
-        "command_args": []
+        "command_description": "show specified/all statistics data",
+        "command_args": [
+          {
+            "item_name" : "stats_item_name",
+            "item_type" : "string",
+            "item_optional": True,
+            "item_default": ""
+          }
+        ]
       },
       {
         "command_name": "set",
-        "command_description": "Set statistics data",
-        "command_args": []
+        "command_description": "set the value of specified name in statistics data",
+        "command_args": [
+          {
+            "item_name" : "stats_data",
+            "item_type" : "map",
+            "item_optional": False,
+            "item_default": {},
+            "map_item_spec": []
+          }
+        ]
       },
       {
-        "command_name": "add",
-        "command_description": "Add statistics data",
-        "command_args": []
+        "command_name": "increase",
+        "command_description": "increase the existent value of specified name in statistics data",
+        "command_args": [
+          {
+            "item_name" : "stats_data",
+            "item_type" : "map",
+            "item_optional": False,
+            "item_default": {},
+            "map_item_spec": []
+          }
+        ]
       },
       {
-        "command_name": "del",
-        "command_description": "Delete statistics data",
-        "command_args": []
+        "command_name": "remove",
+        "command_description": "remove the specified name in statistics data",
+        "command_args": [
+          {
+            "item_name" : "stats_item_name",
+            "item_type" : "string",
+            "item_optional": False,
+            "item_default": ""
+          }
+        ]
       },
       {
         "command_name": "reset",
-        "command_description": "Reset statistics data",
+        "command_description": "reset all statistics data",
         "command_args": []
       },
       {
         "command_name": "shutdown",
-        "command_description": "Shutdown stats module",
-        "command_args": []
-      },
-      {
-        "command_name": "spec",
-        "command_description": "Show stats_spec module",
+        "command_description": "Shut down stats module",
         "command_args": []
       }
-    ],
-    "stats_spec": {
-      "description": "A specification of statistics",
-      "type": "object",
-      "properties": {
-        "report_time": {
-          "title": "Report time",
-          "description": "A date time when stats module reports",
-          "type": "string",
-          "format": "date-time"
-        },
-        "bind10.boot_time": {
-          "title": "stats.BootTime",
-          "description": "A date time when b10-stats process starts",
-          "type": "string",
-          "format": "date-time"
-        },
-        "stats.timestamp": {
-          "title": "stats.Timestamp",
-          "description": "Current timestamp since epoch time (1970-01-01T00:00:00Z)",
-          "type": "float",
-          "format": "second"
-        },
-        "stats.lname": {
-          "title": "stats.LocalName",
-          "description": "A localname of stats module given via CC protocol",
-          "type": "string"
-        },
-        "auth.queries.tcp": {
-          "title": "auth.queries.tcp",
-          "description": "A number of incremental query counts per a process which Auth servers receives in TCP since last sending",
-          "type": "number"
-        },
-        "auth.queries.udp": {
-          "title": "auth.queries.udp",
-          "description": "A number of incremental query counts per a process which Auth servers receives in UDP since last sending",
-          "type": "number"
-        }
-      }
-    }
+    ]
   }
 }

Modified: branches/trac191/src/bin/stats/stats_stub.py.in
==============================================================================
--- branches/trac191/src/bin/stats/stats_stub.py.in (original)
+++ branches/trac191/src/bin/stats/stats_stub.py.in Thu Jul 22 09:28:11 2010
@@ -71,18 +71,18 @@
 class BossStub:
     """
     This class is customized CCSessionStub and is intended to behaves
-    as a Boss process to send to Stats Module.
+    as a virtual Boss process to send to Stats Module.
     """
     def __init__(self, session=None, verbose=False):
         self.stub = CCSessionStub(session=session, verbose=verbose)
     
     def send_command(self):
-        return self.stub.send_command("set", {"bind10.boot_time": get_datetime()})
+        return self.stub.send_command("set", {"stats_data": {"bind10.boot_time": get_datetime()}})
 
 class AuthStub:
     """
     This class is customized CCSessionStub and is intended to behaves
-    as a Auth process to send to Stats Module.
+    as a virtual Auth process to send to Stats Module.
     """
     def __init__(self, session=None, verbose=False):
         self.stub = CCSessionStub(session=session, verbose=verbose)
@@ -91,12 +91,12 @@
     def send_command_udp(self):
         p = "udp"
         self.count[p] = 1
-        return self.stub.send_command("add", {"auth.queries."+p: self.count[p]})
+        return self.stub.send_command("increase", {"stats_data": {"auth.queries."+p: self.count[p]}})
 
     def send_command_tcp(self):
         p = "tcp"
         self.count[p] = self.count[p] + 1
-        return self.stub.send_command("set", {"auth.queries."+p: self.count[p]})
+        return self.stub.send_command("set", {"stats_data": {"auth.queries."+p: self.count[p]}})
 
 def get_timestamp():
     """

Modified: branches/trac191/src/bin/stats/tests/b10-stats_stub_test.py
==============================================================================
--- branches/trac191/src/bin/stats/tests/b10-stats_stub_test.py (original)
+++ branches/trac191/src/bin/stats/tests/b10-stats_stub_test.py Thu Jul 22 09:28:11 2010
@@ -48,7 +48,7 @@
     def test_boss_stub(self):
         env = {'from': None, 'group': 'Stats'}
         result_ok = {'result': [0]}
-        self.assertEqual(('set', {"bind10.boot_time": get_datetime()}, env),
+        self.assertEqual(('set', {"stats_data": {"bind10.boot_time": get_datetime()}}, env),
                          self.boss.send_command())
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
 
@@ -57,7 +57,7 @@
         result_ok = {'result': [0]}
 
         # check command name
-        self.assertTrue( self.auth.send_command_udp()[0] == "add" )
+        self.assertTrue( self.auth.send_command_udp()[0] == "increase" )
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
         self.assertTrue( self.auth.send_command_tcp()[0] == "set" )
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
@@ -69,15 +69,15 @@
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
 
         # check type
-        self.assertTrue( type(self.auth.send_command_udp()[1]["auth.queries.udp"]) == type(int()) )
+        self.assertTrue( type(self.auth.send_command_udp()[1]["stats_data"]["auth.queries.udp"]) == type(int()) )
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
-        self.assertTrue( type(self.auth.send_command_tcp()[1]["auth.queries.tcp"]) == type(int()) )
+        self.assertTrue( type(self.auth.send_command_tcp()[1]["stats_data"]["auth.queries.tcp"]) == type(int()) )
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
 
         # check counter value
-        self.assertTrue(self.auth.send_command_udp()[1]["auth.queries.udp"] == 1) # keep 1
+        self.assertTrue(self.auth.send_command_udp()[1]["stats_data"]["auth.queries.udp"] == 1) # keeps 1
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
-        self.assertTrue(self.auth.send_command_tcp()[1]["auth.queries.tcp"] == 4)
+        self.assertTrue(self.auth.send_command_tcp()[1]["stats_data"]["auth.queries.tcp"] == 4)
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
 
     def tearDown(self):

Modified: branches/trac191/src/bin/stats/tests/b10-stats_test.py
==============================================================================
--- branches/trac191/src/bin/stats/tests/b10-stats_test.py (original)
+++ branches/trac191/src/bin/stats/tests/b10-stats_test.py Thu Jul 22 09:28:11 2010
@@ -21,7 +21,6 @@
 #
 import os
 import time
-import re
 import unittest
 from isc.config.ccsession import ModuleCCSessionError
 from unittest_fakesession import FakeModuleCCSession
@@ -33,14 +32,17 @@
         self.session = FakeModuleCCSession()
         self.subject = SessionSubject(session=self.session, verbose=False)
         self.listener = CCSessionListener(self.subject, verbose=False)
-        self.stats_spec = self.listener.cc_session.get_module_spec().get_full_spec()['stats_spec']
+        self.stats_spec = self.listener.cc_session.get_module_spec().get_config_spec()
         self.stats_data = {
                 'report_time' : get_datetime(),
-                'bind10.boot_time' : '',
+                'bind10.boot_time' : "1970-01-01T00:00:00Z",
                 'stats.timestamp' : float(int(get_timestamp())),
                 'stats.lname' : self.session.lname,
                 'auth.queries.tcp': 0,
-                'auth.queries.udp': 0
+                'auth.queries.udp': 0,
+                "stats.boot_time": get_datetime(),
+                "stats.start_time": get_datetime(),
+                "stats.last_update_time": get_datetime()
                 }
 
     def test_start(self):
@@ -84,7 +86,7 @@
         """
         session = self.session
         subject = self.subject
-        stats_spec = self.stats_spec.copy()
+        stats_spec = self.stats_spec[:]
         stats_data = self.stats_data.copy()
 
         self.assertFalse(subject.running)
@@ -94,99 +96,132 @@
             subject.session.get_message("ConfigManager", None)
 
         # test show command
-        session.group_sendmsg({"command": [ "show" ]}, "Stats")
-        self.assertEqual(len(subject.session.message_queue), 1)
-        subject.check()
-        result_data = subject.session.get_message("Stats", None)
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
-        self.assertEqual({ "result": [ 0, stats_data ]}, result_data)
-        self.assertEqual(len(subject.session.message_queue), 0)
+        session.group_sendmsg({"command": [ "show", None ]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        result_data = subject.session.get_message("Stats", None)
+        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
+        self.assertEqual({ "result": [ 0, stats_data ]}, result_data)
+        self.assertEqual(len(subject.session.message_queue), 0)
+
+        # test show command with args
+        session.group_sendmsg({"command": [ "show", {"stats_item_name": "stats.lname"}]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        result_data = subject.session.get_message("Stats", None)
+        self.assertEqual({ "result": [ 0, {'stats.lname': stats_data['stats.lname']} ]}, result_data)
+        self.assertEqual(len(subject.session.message_queue), 0)
+
+        # test show command with args which has no valid key name
+        session.group_sendmsg({"command": [ "show", {"stats_item_name": "stats.dummy"}]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        result_data = subject.session.get_message("Stats", None)
+        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
+        self.assertEqual({ "result": [ 0, stats_data ]}, result_data)
+        self.assertEqual(len(subject.session.message_queue), 0)
+
+        # sleep just one second
+        time.sleep(1)
 
         # test set command
         stats_data['atest'] = float(1.0)
-        session.group_sendmsg({"command":
-                                   [ "set",
-                                     {'atest' : stats_data['atest']}
-                                     ]}, "Stats")
-        self.assertEqual(len(subject.session.message_queue), 1)
-        subject.check()
-        self.assertEqual(result_ok(),
-                         subject.session.get_message("Stats", None))
-        self.assertEqual(len(subject.session.message_queue), 0)
-
-        # test show command
-        session.group_sendmsg({"command": [ "show" ]}, "Stats")
-        self.assertEqual(len(subject.session.message_queue), 1)
-        subject.check()
-        result_data = subject.session.get_message("Stats", None)
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
+        session.group_sendmsg({"command": [ "set", {'stats_data': {'atest': stats_data['atest']}}]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        self.assertEqual(result_ok(),
+                         subject.session.get_message("Stats", None))
+        self.assertEqual(len(subject.session.message_queue), 0)
+
+        # test show command
+        session.group_sendmsg({"command": [ "show", None ]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        result_data = subject.session.get_message("Stats", None)
+        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
+        stats_data['report_time'] = get_datetime()
+        stats_data['stats.last_update_time'] = get_datetime()
+        stats_data['stats.timestamp'] = float(int(get_timestamp()))
         self.assertEqual(result_ok(0, stats_data), result_data)
         self.assertEqual(len(subject.session.message_queue), 0)
 
-        # test add command
+        # sleep just one second
+        time.sleep(1)
+
+        # test increase command
         stats_data['atest'] = stats_data['atest'] + float(0.1)
-        session.group_sendmsg({"command": [ "add", {'atest': float(0.1) } ]}, "Stats")
-        self.assertEqual(len(subject.session.message_queue), 1)
-        subject.check()
-        self.assertEqual(result_ok(),
-                         subject.session.get_message("Stats", None))
-        self.assertEqual(len(subject.session.message_queue), 0)
-
-        # test show command
-        session.group_sendmsg({"command": [ "show" ]}, "Stats")
-        self.assertEqual(len(subject.session.message_queue), 1)
-        subject.check()
-        result_data = subject.session.get_message("Stats", None)
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
-        self.assertEqual({ "result": [ 0, stats_data ]}, result_data)
-        self.assertEqual(len(subject.session.message_queue), 0)
-
-        # test del command
+        session.group_sendmsg({"command": [ "increase", {'stats_data': {'atest': float(0.1) }} ]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        self.assertEqual(result_ok(),
+                         subject.session.get_message("Stats", None))
+        self.assertEqual(len(subject.session.message_queue), 0)
+
+        # test show command
+        session.group_sendmsg({"command": [ "show", None ]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        result_data = subject.session.get_message("Stats", None)
+        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
+        stats_data['report_time'] = get_datetime()
+        stats_data['stats.last_update_time'] = get_datetime()
+        stats_data['stats.timestamp'] = float(int(get_timestamp()))
+        self.assertEqual({ "result": [ 0, stats_data ]}, result_data)
+        self.assertEqual(len(subject.session.message_queue), 0)
+
+        # test remove command with args
         stats_data.pop('atest')
-        session.group_sendmsg({"command": [ "del", 'atest' ]}, "Stats")
-        self.assertEqual(len(subject.session.message_queue), 1)
-        subject.check()
-        self.assertEqual(result_ok(),
-                         subject.session.get_message("Stats", None))
-        self.assertEqual(len(subject.session.message_queue), 0)
-
-        # test show command
-        session.group_sendmsg({"command": [ "show" ]}, "Stats")
-        self.assertEqual(len(subject.session.message_queue), 1)
-        subject.check()
-        result_data = subject.session.get_message("Stats", None)
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
-        self.assertEqual({ "result": [ 0, stats_data ]}, result_data)
-        self.assertEqual(len(subject.session.message_queue), 0)
+        session.group_sendmsg({"command": [ "remove", {"stats_item_name": 'atest' }]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        self.assertEqual(result_ok(),
+                         subject.session.get_message("Stats", None))
+        self.assertEqual(len(subject.session.message_queue), 0)
+
+        # test remove command with args which has no valid key name
+        session.group_sendmsg({"command": [ "remove", {"stats_item_name": "stats.dummy"}]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        self.assertEqual(result_ok(1,"''"),
+                         subject.session.get_message("Stats", None))
+        self.assertEqual(len(subject.session.message_queue), 0)
+
+        # test show command
+        session.group_sendmsg({"command": [ "show", None ]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        result_data = subject.session.get_message("Stats", None)
+        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
+        self.assertEqual({ "result": [ 0, stats_data ]}, result_data)
+        self.assertEqual(len(subject.session.message_queue), 0)
+
+        # sleep one second
+        time.sleep(1)
 
         # test reset command
         stats_data = self.stats_data.copy()
-        session.group_sendmsg({"command": [ "reset" ]}, "Stats")
-        self.assertEqual(len(subject.session.message_queue), 1)
-        subject.check()
-        self.assertEqual(result_ok(),
-                         subject.session.get_message("Stats", None))
-        self.assertEqual(len(subject.session.message_queue), 0)
-
-        # test show command
-        session.group_sendmsg({"command": [ "show" ]}, "Stats")
-        self.assertEqual(len(subject.session.message_queue), 1)
-        subject.check()
-        result_data = subject.session.get_message("Stats", None)
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
-        self.assertEqual({ "result": [ 0, stats_data ]}, result_data)
-        self.assertEqual(len(subject.session.message_queue), 0)
-
-        # test show spec command
-        session.group_sendmsg({"command": [ "spec" ]}, "Stats")
-        self.assertEqual(len(subject.session.message_queue), 1)
-        subject.check()
-        self.assertEqual(result_ok(0, stats_spec),
-                         subject.session.get_message("Stats", None))
+        session.group_sendmsg({"command": [ "reset", None ]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        self.assertEqual(result_ok(),
+                         subject.session.get_message("Stats", None))
+        self.assertEqual(len(subject.session.message_queue), 0)
+
+        # test show command
+        session.group_sendmsg({"command": [ "show", None ]}, "Stats")
+        self.assertEqual(len(subject.session.message_queue), 1)
+        subject.check()
+        result_data = subject.session.get_message("Stats", None)
+        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
+        stats_data['report_time'] = get_datetime()
+        stats_data['stats.last_update_time'] = get_datetime()
+        stats_data['stats.timestamp'] = float(int(get_timestamp()))
+        stats_data['stats.start_time'] = get_datetime()
+        self.assertEqual({ "result": [ 0, stats_data ]}, result_data)
         self.assertEqual(len(subject.session.message_queue), 0)
 
         # test status command
-        session.group_sendmsg({"command": [ "status" ]}, "Stats")
+        session.group_sendmsg({"command": [ "status", None ]}, "Stats")
         self.assertEqual(len(subject.session.message_queue), 1)
         subject.check()
         self.assertEqual(result_ok(0, "I'm alive."),
@@ -194,7 +229,7 @@
         self.assertEqual(len(subject.session.message_queue), 0)
 
         # test unknown command
-        session.group_sendmsg({"command": [ "hoge" ]}, "Stats")
+        session.group_sendmsg({"command": [ "hoge", None ]}, "Stats")
         self.assertEqual(len(subject.session.message_queue), 1)
         subject.check()
         self.assertEqual(result_ok(1, "Unknown command: 'hoge'"),
@@ -202,7 +237,7 @@
         self.assertEqual(len(subject.session.message_queue), 0)
 
         # test shutdown command
-        session.group_sendmsg({"command": [ "shutdown" ]}, "Stats")
+        session.group_sendmsg({"command": [ "shutdown", None ]}, "Stats")
         self.assertEqual(len(subject.session.message_queue), 1)
         self.assertTrue(subject.running)
         subject.check()




More information about the bind10-changes mailing list