#!/usr/bin/env python
import logging
import os,sys,time,socket,threading,copy,StringIO,cPickle,subprocess,fcntl,struct,signal,shutil,commands
import re,ConfigParser
import platform

def fPopen(aCmd):
    p=subprocess.Popen(aCmd, shell=True, bufsize=4096,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
    sOut = p.stdout.read()
    sErr = p.stderr.read()
    return (sOut,sErr)

def main():
    if (os.path.exists("/sys/fs/cgroup/cpu/cpu.cfs_period_us") or os.path.exists("/cgroup/cpu/cpu.cfs_period_us")):
        #print "cgroup is installed, no need to install again"
        return
    arrOs=['','ubuntu','centos','fedora','rhel','suse','asianux','debian','else']
    arrOsDes=['','ubuntu','centos','fedora','hat','suse','asianux','debian','else']
    sOut,sErr = fPopen("cat /etc/issue;cat /etc/redhat-release")
    sIssueRes = sOut.lower()
    iSelect = 0
    idxArrOs = 1
    while (idxArrOs <= 7):
        if (sIssueRes.find(arrOsDes[idxArrOs]) != -1):
            iSelect = idxArrOs
            break
        else:
            idxArrOs += 1
    #print sOut

    sOut,sErr = fPopen("cat /etc/lsb-release | grep DISTRIB_RELEASE | awk -F '=' '{print $2}'")
    if (sOut == ""):
        sOut,sErr = fPopen("cat /etc/issue | grep release | awk '{for (i = 1; i < NF; i++) if ($i == \"release\") print $(i+1)}'")
        if (sOut == ""):
            sOut,sErr = fPopen("cat /etc/redhat-release | grep release | awk '{for (i = 1; i < NF; i++) if ($i == \"release\") print $(i+1)}'")
    version = sOut
    
    if (version == ""):
        print "Get system version fail, do not enable cgroup"
        return
    version = version.strip('\n')
    #print version

    sOut,sErr = fPopen("getconf LONG_BIT")
    if (int(sOut) == 32):
        longbit = "86"
    else:
        longbit = "64"

    pkgpath = "./dependpkg/cgroup/x" + longbit + "/" + arrOs[idxArrOs] + "/" + version + "/"
    #print pkgpath

    #pkgpath = "./dependpkg/cgroup/x64/centos/6.4/"
    #pkgpath = "./dependpkg/cgroup/x64/ubuntu/14.04/"
    cmd=""
    if (arrOs[idxArrOs] == 'centos' or arrOs[idxArrOs] == 'rhel'):
        cmd = "rpm -ih "
        for filename in os.listdir(pkgpath):
            cmd += pkgpath + filename + " "
    elif (arrOs[idxArrOs] == 'ubuntu'):
        cmd = "dpkg -i "
        for filename in os.listdir(pkgpath):
            cmd += pkgpath + filename + " "
    else:
        print "System cgroup is disabled"
        return 
    #print cmd
    sOut,sErr = fPopen(cmd)
    #print sOut
    #print sErr
    if (arrOs[idxArrOs] == 'centos' or arrOs[idxArrOs] == 'rhel'):
        if (version.find("6.") != -1):
            sOut,sErr = fPopen("service cgconfig start; chkconfig cgconfig on")
            #print sOut
            #print sErr

if __name__ == "__main__":
    main()
    sys.exit(0)
