Commits

Vladimir Rusinov  committed c41773b

fix for vm.memory.{in,}active

  • Participants
  • Parent commits d5fa68f

Comments (0)

Files changed (14)

File src/vm_memory.py

         inavtive - amount of inactive (not accessed recently) memory
 """
 
-import sys
+from ztc.vm.memory import Memory
 
-from ztc.vm.memory import Memory
-from ztc import notsupported
 
-if len(sys.argv) != 2:
-    notsupported("not enough arguments")
-
-metric = sys.argv[1]
-
-try:
-    m = Memory()
-
-    print m.__getattribute__(metric)
-except Exception, e:
-    notsupported(e)
+c = Memory()
+m = c.args[0]
+c.get(m, *c.args[1:])

File src/ztc/check.py

 import ConfigParser
 import logging  # @UnusedImport
 import logging.handlers  # @UnusedImport
-from tempfile import mktemp
 
 import unittest
 
     test = False
     logger = None
 
-    def __init__(self, name=None, test=False):
+    def __init__(self, name=None):
         if name:
             self.name = name
         if self.name == 'ztccheck':
         # checking if we are running in debug mode
         if self.config.get('debug', False):
             self.debug = True
-        # checking if we are running inside test
-        if test:
-            self.test = True
-            self.debug = True
-            self.options.logfile = mktemp()
 
+        self._setup_logging()
+        self._myinit()
+
+    def _setup_logging(self):
+        """Setup logging - self.logger"""
         # setup logger
         self.logger = logging.getLogger(self.__class__.__name__)
         formatter = logging.Formatter(
         self.logger.debug("config file: %s" % \
                           os.path.join(self.options.confdir,
                           self.name + ".conf"))
-        self._myinit()
 
     def _myinit(self):
         """ To be overriden by subclasses, executes just after __init__ -
         self.args = args
         if self.OPTPARSE_MIN_NUMBER_OF_ARGS > self.OPTPARSE_MAX_NUMBER_OF_ARGS:
             self.OPTPARSE_MAX_NUMBER_OF_ARGS = self.OPTPARSE_MIN_NUMBER_OF_ARGS
-        if len(self.args) < self.OPTPARSE_MIN_NUMBER_OF_ARGS:
-            raise CheckFail("Not enough arguments")
-        if len(self.args) > self.OPTPARSE_MAX_NUMBER_OF_ARGS:
-            raise CheckFail("Too many arguments")
+        #number_of_args = len(self.args)
+        #if number_of_args < self.OPTPARSE_MIN_NUMBER_OF_ARGS:
+        #    raise CheckFail("Not enough arguments")
+        #if number_of_args > self.OPTPARSE_MAX_NUMBER_OF_ARGS:
+        #    raise CheckFail("Not enough arguments")
 
     def version(self):
         """ print version information """
         config.read(os.path.join(self.options.confdir, self.name + ".conf"))
         return config
 
-    def _get(self, *args, **kwargs):
+    def _get(self, metric, *args, **kwargs):
         """This method MUST return exactly one string or integer or raise
         one of CheckFail or CheckTimeout exceptions. Multiple return values
-        are not supported by zabbix yet."""
-        raise NotImplementedError("Class %s must reimplement _get method"
-                                            % (self.__class__.__name__,))
+        are not supported by zabbix yet. Default behavour is to return
+        attribute name. Should be overriden if more params needed"""
+        return self.__getattribute__(metric)
 
     def get_val(self, metric=None, *args, **kwargs):
         """ wrapper above _get to ensure every returned value is in

File src/ztc/lib/flup_fcgi_client.py

 
     return s + name + value
 
+
 class Record(object):
     """
     A FastCGI Record.
 
     Used for encoding/decoding records.
     """
+
     def __init__(self, typ=FCGI_UNKNOWN_TYPE, requestId=FCGI_NULL_REQUEST_ID):
         self.version = FCGI_VERSION_1
         self.type = typ
 
     def write(self, sock):
         """Encode and write a Record to a socket."""
-        self.paddingLength = -self.contentLength & 7
+        self.paddingLength = - self.contentLength & 7
 
         if __debug__:
             _debug(9, 'write: fd = %d, type = %d, requestId = %d, '
         if self.paddingLength:
             self._sendall(sock, '\x00' * self.paddingLength)
 
+
 class FCGIApp(object):
 
     def __init__(self, connect=None, host=None, port=None, filterEnviron=True):
             return sock
 
         # To be done when I have more time...
-        raise NotImplementedError('Launching and managing FastCGI programs not yet implemented')
+        raise NotImplementedError(
+            'Launching and managing FastCGI programs not yet implemented')
 
     def _fcgiGetValues(self, sock, vars):  # @ReservedAssignment
         # Construct FCGI_GET_VALUES record

File src/ztc/pgsql/pgcluster.py

 
     dbs = []
 
-    def _get(self, metric, *args, **kwargs):
-        if metric == 'bloat':
-            return self.get_bloat()
-        else:
-            raise CheckFail('uncknown metric')
-
-    def get_bloat(self):
+    @property
+    def bloat(self):
         """ get max database bloat of all databases of cluster """
-        q = pgq.BLOAT
+        query = pgq.BLOAT
         pages = 0
         otta = 0
         bloatest = [] # list of bloatest tables
-        ret = self.query_eachdb(q, exclude=['template0'])
+        ret = self.query_eachdb(query, exclude=['template0'])
         for db in ret.keys():
             # loop through all databases
             for r in ret[db]:

File src/ztc/pgsql/pgdb.py

 #!/usr/bin/env python
 """
 PgDB class - ZTCCheck for tracking single postgresql database
-    
+
 Copyright (c) 2010-2011 Vladimir Rusinov <vladimir@greenmice.info>
 
 Requirements:
 
 class PgDB(ZTCCheck):
     """ Connection to single database """
-    
+
     name = 'pgsql'
     dbconn = None
-    
+
     OPTPARSE_MIN_NUMBER_OF_ARGS = 1
     OPTPARSE_MAX_NUMBER_OF_ARGS = 3
-    
+
     def _myinit(self):
         connect_dict = {
             'host': self.config.get('host', None),  # none = connect via socket
             'database': self.config.get('database', 'postgres')
         }
         self.dbconn = PgConn(connect_dict, self.logger)
-    
+
     def _get(self, metric, *args, **kwargs):
         if metric == 'query':
             q = args[0]
             if m == 'num':
                 return self.get_wal_num()
             else:
-                CheckFail('uncknown wal metric: %s' % m)                            
+                CheckFail('uncknown wal metric: %s' % m)
         else:
             raise CheckFail('uncknown metric %s' % metric)
-        
+
     def get_fsm(self, metric):
         """ PostgreSQL freespacemap metrics.
         Requirements: pg_freespacement, PostgreSQL <= 8.3"""
         q = pgq.FSM[metric]
         ret = self.dbconn.query(q)[0][0]
         return ret
-    
+
     def get_buffers(self, metric):
         """ PostgreSQL buffer metrics: number of clear/dirty/used/total
         buffers.
         q = pgq.BUFFER[metric]
         ret = self.dbconn.query(q)[0][0]
         return ret
-        
+
     def get_dbstat(self, m):
         """ get sum of passed metric from dbstat """
         q = "SELECT SUM(%s) FROM pg_stat_database" % m
         ret = self.dbconn.query(q)[0][0]
         return ret
-        
+
     def get_conn_nr(self, state):
         """ Get number of connections in given state """
         q = pgq.CONN_NUMBER[state]
         ret = self.dbconn.query(q)[0][0]
         return ret
-        
+
     def get_tnx_age(self, state):
         """ Get max age of transactions in given state.
         Supported states are: 'running', 'idle_tnx'
             q = pgq.TNX_AGE_RUNNING
         else:
             raise CheckFail("uncknown transaction state requested")
-        
+
         ret = self.dbconn.query(q)
         if ret:
             ret = ret[0][0]
         else:
             # no rows returned => no transactions in given state
             return 0
-    
+
     def get_ping(self):
         """get amount of time required to execute trivial query"""
         st = time.time()
             else:
                 return 0
         except:
-            return 0        
-    
+            return 0
+
     def get_autovac_freeze(self):
         """ Checks how close each database is to the Postgres
             autovacuum_freeze_max_age setting. This action will only work for
             databases version 8.2 or higher. The 'age' of the transactions in
             each database is compared to the autovacuum_freeze_max_age setting
             (200 million by default) to generate a rounded percentage.
-        
+
         Returns: (float) maximum age of transaction from all databases, in %
             (compared to autovacuum_freeze_max_age)
         """
         for (freeze, age, percent, dbname) in ret:  # @UnusedVariable
             if self.debug:
                 self.logger.info("Freeze %% for %s: %s" % (dbname, percent))
-            max_percent = max(max_percent, percent)        
+            max_percent = max(max_percent, percent)
         return max_percent
 
     def get_locks(self, m, mm=None):
             q = pgq.LOCKS[m]
         ret = self.dbconn.query(q)[0][0]
         return ret
-    
+
     def get_wal_num(self):
         """ get number of wal files in pg_xlog directory """
         q = pgq.WAL_NUMBER

File src/ztc/tests/__init__.py

+#!/usr/bin/env python
+"""ZTC-wide test customs functions and mocks"""
+
+import os
+import logging
+
+
+def setup_no_logging(self):
+    """Mock for ZTCCheck._setup_logging function"""
+    # setup logger
+    self.logger = logging.getLogger(self.__class__.__name__)
+    formatter = logging.Formatter(
+        "[%(name)s] %(asctime)s - %(levelname)s: %(message)s")
+
+    sh = logging.StreamHandler()
+    sh.setLevel(logging.DEBUG)
+    self.logger.setLevel(logging.DEBUG)
+    sh.setFormatter(formatter)
+    self.logger.addHandler(sh)
+    self.logger.debug("created")
+    self.logger.debug("config file: %s" % \
+                      os.path.join(self.options.confdir,
+                      self.name + ".conf"))

File src/ztc/tests/hw/__init__.py

-#!/usr/bin/env python
-#pylint: disable=W0212
-"""
-test for ztc.hw.RAID_3Ware
-
-This file is part of ZTC
-
-Copyright (c) 2012 Wrike, Inc. [http://www.wrike.com/]
-"""
-
-import unittest
-from ztc.hw import RAID_3Ware
-
-
-class TestRAID_3Ware(unittest.TestCase):
-    """ Tests for RAID_3Ware class """
-
-    def test_get_status(self):
-        """ test parsing of status output """
-        key = (0, 0, 'status')
-        r = RAID_3Ware(test=True)
-
-        # 1: Ok message
-        r._tw_out[key] = "/c0/u0 status = OK\n\n"
-        self.assertEquals(r.get_status(), 'OK')
-
-        # 2: fail message
-        r._tw_out[key] = "/c0/u0 status = FAIL"
-        self.assertEquals(r.get_status(), 'FAIL')
-
-        # 3: no message
-        r._tw_out[key] = ""
-        self.assertEquals(r.get_status(), 'ZTC_FAIL: TW_CLI')
-
-        # 4: wrong type
-        r._tw_out[key] = ()
-        self.assertEquals(r.get_status(), 'ZTC_FAIL: popen')
-        r._tw_out[key] = None
-        self.assertEquals(r.get_status(), 'ZTC_FAIL: popen')
-        r._tw_out[key] = 123
-        self.assertEquals(r.get_status(), 'ZTC_FAIL: popen')
-
-if __name__ == '__main__':
-    unittest.main()

File src/ztc/tests/hw/test_hw.py

+#!/usr/bin/env python
+#pylint: disable=W0212
+"""
+test for ztc.hw.RAID_3Ware
+
+This file is part of ZTC
+
+Copyright (c) 2012 Wrike, Inc. [http://www.wrike.com/]
+"""
+
+import unittest
+from ztc.hw import RAID_3Ware
+
+
+class TestRAID_3Ware(unittest.TestCase):
+    """ Tests for RAID_3Ware class """
+
+    def test_get_status(self):
+        """ test parsing of status output """
+        key = (0, 0, 'status')
+        r = RAID_3Ware(test=True)
+
+        # 1: Ok message
+        r._tw_out[key] = "/c0/u0 status = OK\n\n"
+        self.assertEquals(r.get_status(), 'OK')
+
+        # 2: fail message
+        r._tw_out[key] = "/c0/u0 status = FAIL"
+        self.assertEquals(r.get_status(), 'FAIL')
+
+        # 3: no message
+        r._tw_out[key] = ""
+        self.assertEquals(r.get_status(), 'ZTC_FAIL: TW_CLI')
+
+        # 4: wrong type
+        r._tw_out[key] = ()
+        self.assertEquals(r.get_status(), 'ZTC_FAIL: popen')
+        r._tw_out[key] = None
+        self.assertEquals(r.get_status(), 'ZTC_FAIL: popen')
+        r._tw_out[key] = 123
+        self.assertEquals(r.get_status(), 'ZTC_FAIL: popen')
+
+if __name__ == '__main__':
+    unittest.main()

File src/ztc/tests/system/test_time.py

+#!/usr/bin/env python
+"""
+test for ztc.system.time check
+
+This file is part of ZTC
+
+Copyright (c) 2012 Vladimir Rusinov <vladimir@greenmice.info>
+
+License: GNU GPL 3
+"""
+
+import unittest
+
+from ztc.system.time import TimeCheck
+
+
+class TestTime(unittest.TestCase):
+    """Test for ztc.system.time.TimeCheck class"""
+
+    def setUp(self):
+        self.failed_ntp_check = TimeCheck()
+        self.failed_ntp_check._timeout = 0.1
+        self.failed_ntp_check._ntp_addr = "example.com"
+
+        self.ntp_check = TimeCheck()
+
+    def test_offset(self):
+        """Positive test. requires network"""
+        assert isinstance(self.ntp_check.offset, float), "Offset is not float"
+
+    def test_offset_ntp_dead(self):
+        """Test offset when ntp server is dead"""
+        assert self.failed_ntp_check.offset == 3600
+
+    def test_delay(self):
+        assert isinstance(self.ntp_check.delay, float), "Delay is not float"
+
+    def test_delay_fail(self):
+        assert self.failed_ntp_check.offset == 3600
+
+    def test_precision(self):
+        assert isinstance(self.ntp_check.precision, float), \
+            "Delay is not float"
+        assert self.ntp_check.precision < 2, "Precision is >= 2"
+
+    def test_precision_fail(self):
+        p = self.failed_ntp_check.precision
+        assert p == 2, "Failed precision is not 2, %i instead" % p
+
+    def test_uncknown_metric(self):
+        try:
+            self.assertRaises(AttributeError, self.ntp_check.none)
+            self.assertRaises(AttributeError, self.ntp_check._get('none'))
+        except AttributeError:
+            # we don't want this test to fail
+            pass
+
+if __name__ == '__main__':
+    unittest.main()

File src/ztc/tests/system/time.py

-#!/usr/bin/env python
-"""
-test for ztc.system.time check
-
-This file is part of ZTC
-
-Copyright (c) 2012 Vladimir Rusinov <vladimir@greenmice.info>
-
-License: GNU GPL 3
-"""
-
-import unittest
-
-from ztc.system.time import TimeCheck
-
-
-class TestTime(unittest.TestCase):
-    """Test for ztc.system.time.TimeCheck class"""
-
-    def setUp(self):
-        self.failed_ntp_check = TimeCheck()
-        self.failed_ntp_check._timeout = 0.1
-        self.failed_ntp_check._ntp_addr = "example.com"
-
-        self.ntp_check = TimeCheck()
-
-    def test_offset(self):
-        """Positive test. requires network"""
-        assert isinstance(self.ntp_check.offset, float), "Offset is not float"
-
-    def test_offset_ntp_dead(self):
-        """Test offset when ntp server is dead"""
-        assert self.failed_ntp_check.offset == 3600
-
-    def test_delay(self):
-        assert isinstance(self.ntp_check.delay, float), "Delay is not float"
-
-    def test_delay_fail(self):
-        assert self.failed_ntp_check.offset == 3600
-
-    def test_precision(self):
-        assert isinstance(self.ntp_check.precision, float), \
-            "Delay is not float"
-        assert self.ntp_check.precision < 2, "Precision is >= 2"
-
-    def test_precision_fail(self):
-        p = self.failed_ntp_check.precision
-        assert p == 2, "Failed precision is not 2, %i instead" % p
-
-    def test_uncknown_metric(self):
-        try:
-            self.assertRaises(AttributeError, self.ntp_check.none)
-            self.assertRaises(AttributeError, self.ntp_check._get('none'))
-        except AttributeError:
-            # we don't want this test to fail
-            pass
-
-if __name__ == '__main__':
-    unittest.main()

File src/ztc/tests/test_check.py

 import unittest
 
 from ztc.check import ZTCCheck
+from ztc.tests import setup_no_logging
+
+ZTCCheck._setup_logging = setup_no_logging
+
 
 class ZTCCheckTest(unittest.TestCase):
     """ Test for ZTCCheck class """
         self.assertEqual(ch.get_val(8.1e-05), '0.000081')
         self.assertEqual(ch.get_val(100000.0), '100000')
         self.assertEqual(ch.get_val(0.0), '0')
-        self.assertEqual(ch.get_val(0.33333333333333333333333), '0.333333')
+        self.assertEqual(ch.get_val(0.33333333333333333333333), '0.333333')

File src/ztc/tests/vm/__init__.py

Empty file added.

File src/ztc/tests/vm/test_memory.py

+#!/usr/bin/env python
+"""ztc.vm.memory tests"""
+
+import unittest
+
+from ztc.vm.memory import Memory
+
+
+class Test(unittest.TestCase):
+
+    def test_get_active(self):
+        m = Memory()
+        assert isinstance(m.active, long)
+
+
+if __name__ == "__main__":
+    #import sys;sys.argv = ['', 'Test.testName']
+    unittest.main()

File src/ztc/vm/memory.py

 Copyright (c) 2011 Vladimir Rusinov <vladimir@greenmice.info>
 """
 
-class Memory(object):
+from ztc.check import ZTCCheck
+
+
+class Memory(ZTCCheck):
+    name = 'memory'
+
     def _get_amount(self, name):
         """ Get amount of %name% memory from /proc/meminfo
             @param name: memory metric name (string)
         for l in f.readlines():
             if l.startswith('%s: ' % name):
                 r = l.split()[-2]
-        return int(r)*1024
-    
-    def get_active(self):
+        return long(r) * 1024
+
+    @property
+    def active(self):
         return self._get_amount('Active')
-    active = property(get_active)
-    
-    def get_inactive(self):
+
+    @property
+    def inactive(self):
         """ Get amount of inactive memory """
         return self._get_amount('Inactive')
-    inactive = property(get_inactive)
-    
+
     def get_used(self):
         """ Get amount of used (by apps) memory """
         return self._get_amount('MemTotal') - self._get_amount('MemFree') - \
             self._get_amount('Buffers') - self._get_amount('Cached')
-    used = property(get_used) 
+    used = property(get_used)
 
 if __name__ == '__main__':
     m = Memory()
     print "Used: ", m.used
     print "Active: ", m.active
-    print "Inactive: ", m.inactive 
+    print "Inactive: ", m.inactive