#!/usr/bin/env python
#
# Appliance specific performance and optimization settings
# F10: 	* clean disk-cache if number of order 2/3/4 pages are too small
#	* 

# Overview of /proc/sys/vm (see kernel Documentation/sysctl/vm.txt for details)
#		* swappiness: control swapping of memory pages 
#							values: 100 (aggressive swapping)
#								 60 (default)
#								  0 (no swapping)
#
#		* vfs_cache_pressure: control if page-cache is used for data or inodes/dentries
#		  values:	100 -> fair rate
#				<100  -> retain dentries and inodes
#				>100  -> prefer to reclaim dentries and inodes
#				DO NOT SET TO 0 ! MAY LEED TO OOM-CONDITION
#
#		* dirty_background_ratio: defines when pdflush should start writeback
#		  dirty_background_bytes: 
#		* dirty_ration:		  define when a writing app must write back dirty pages
#		  dirty_bytes
#		* dirty_writeback_centisecs: interval of pdflush writeback daemon
#		* dirty_expire_centisecs: maximum lifetime of dirty pages. must be written after
#					  defined centisecs (defaut: 3000 [30s])
#
#		* drop_caches: allows a user to force the drop/free of all unused cached pages
#			       should be used very carefully, may decrease performance
#
#		* min_free_kbytes: minimum of free memory the kernel should keep
import os
import sys
import commands

#### INTERNAL FUNCTIONS ######
# get appliance name
def getApplianceName():
    '''
    Get appliance name
    '''
    applName = ""
    if (os.path.exists('/opt/phion/run/appliance.state')):
        f = None
        try:
            f = open('/opt/phion/run/appliance.state')
            line = f.readline()
            while (line != ''):
                line = line.strip()
                if (line.startswith('MODEL = ')):
                    # strip 'MODEL = '
                    applName = line[8:]
                    break
                line = f.readline()
            
        except Exception, e:
            # let's invoke hwtool
            pass
        finally:
            if (f):
                f.close()
        
    if (applName == ""):
        (_status, _output) = commands.getstatusoutput('/opt/phion/bin/hwtool -m')
        applName = _output.strip()

    return applName


# get memory triple
def getMemory():
    '''
    Return list of memory, (total, free, cached)
    '''
    memf = 0.0
    memt = 0.0
    memc = 0.0
    f = None
    try:
        f = open('/proc/meminfo')
        line = f.readline()
        while (line != ''):
            if (line.startswith('MemTotal:')):
                memt = float(line[10:-4].strip())
            elif (line.startswith('MemFree:')):
                memf = float(line[10:-4].strip())
            elif (line.startswith('Cached:')):
                memc = float(line[10:-4].strip())
            line = f.readline()
        f.close()
    except Exception, e:
        pass
    finally:
        if (f):
            f.close()
    return (memt, memf, memc)

# write a sysctl
def writeSysctl(path, val):
    '''
    Update a sysctl value
    '''
    try:
        dc = open("/proc/sys/" + path.replace('.', '/'), 'w')
        print >> dc, val
        dc.close()
    except Exception, ioe:
        print ioe
        return 1
    return 0
    

#### FUNCTIONS ######

# Drop cached pages
def dropCaches(level):
    '''
    Drop Page-Cache, dentries and inode cache
    level: 1 ... drop page-cache
           2 ... drop dentries and inodes
           3 ... drop both
    '''
    return writeSysctl('vm.drop_caches', level)

def setMinFree(min_free):
    '''
    Set minimum reserved kernel memory in kByte
    '''
    return writeSysctl('vm.min_free_kbytes', min_free)



#### APPLIANCE HANDLER #####

# F10 
def F10():
    '''
    F10 specific actions, clear page-cache, dentries and inode cache
    '''
    setMinFree(10000)
    (memtotal, memfree, memcache) = getMemory()
    pctfree = float(float(memfree) / float(memtotal))
    pctcache = float(float(memcache) / float(memtotal))
    if (pctfree < 0.1 and pctcache > 0.05):
        dropCaches(3)
    return 0

# APPLIANCE MAPPING
# define function which must be called for a given appliance
cmds = {
    'F10' : F10,
    'F10b' : F10,
    'NF-EDGE' : F10,
    'NF-CASH' : F10,
}


# MAIN
# return 42 if nothing has to be done (control will no reinvoke us)
def main():
    applname = getApplianceName()
    try:
        ret = 42;
        if (cmds.has_key(applname)):
            ret = cmds[applname]()
        sys.exit(ret)
    except Exception, e:
        print e
        sys.exit(1)
    sys.exit(42)

if __name__ == "__main__":
    main()
