#!/usr/bin/env python
# -*- coding: utf-8 -*-

# LXCF - LXC Facility
# Copyright (C) 2013-2014 FUJITSU LIMITED

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

import sys
import os
import json
from optparse import OptionParser

# check root
if os.geteuid():
    print("error: Because you are not root, you cannot execute this command.")
    sys.exit(1)

parser = OptionParser()
(options, args) = parser.parse_args(sys.argv)
argc = len(args)

if not 2 <= argc <= 3:
    print("usage: lxcf load LXCNAME [JSON_FILE]")
    sys.exit(1)

LXCNAME = args[1]

RESOURCEFILE = "/etc/lxcf/rsc/" + LXCNAME + "/resource.val"

if argc == 2:
    RESOURCEFILE2 = ""
else:
    RESOURCEFILE2 = args[2]


def checkKMG(val):
    """The unit of "K,M,G" is converted."""
    last = val[-1:]
    if val == "-":
        return val
    elif last == "k" or last == "K":
        return str(int(float(val[:-1]) * 1024))
    elif last == "M" or last == "m":
        return str(int(float(val[:-1]) * 1024 ** 2))
    elif last == "G" or last == "g":
        return str(int(float(val[:-1]) * 1024 ** 3))
    elif last == "T" or last == "t":
        return str(int(float(val[:-1]) * 1024 ** 4))
    else:
        return str(val)


def blkio_val(val):
    """The unit of blkio is converted."""
    s = val.split()
    if len(s) != 2:
        print("illegal blkio value")
        sys.exit(1)
    s2 = checkKMG(s[1])
    return s[0] + " " + s2

# load resource json file
try:
    f = open(RESOURCEFILE)
except:
    print("can't open: " + RESOURCEFILE)
    sys.exit(1)

try:
    data = json.load(f)
except:
    print("illegal json file: " + RESOURCEFILE)
    f.close()
    sys.exit(1)

f.close()

# load parameter resource json file
data2 = []
if argc == 3:
    try:
        f2 = open(RESOURCEFILE2)
    except:
        print("can't open:" + RESOURCEFILE2)
        sys.exit(1)

    try:
        data2 = json.load(f2)
    except:
        print("illegal json file:" + RESOURCEFILE2)
        f2.close()
        sys.exit(1)

    data = data2
    f2.close()

# get resource date
try:
    name = data['name']
except:
    pass

try:
    cpun = data['cpun']
except:
    pass

try:
    cpurate = data['cpurate']
except:
    pass

try:
    numa = data['numa']
except:
    pass

try:
    memlimit = checkKMG(data['memlimit'])
except:
    pass

try:
    memswlimit = checkKMG(data['memswlimit'])
except:
    pass

try:
    blkio_r = data['blkio_r']
except:
    pass

try:
    blkio_w = data['blkio_w']
except:
    pass

try:
    blkiops_r = data['blkiops_r']
except:
    pass

try:
    blkiops_w = data['blkiops_w']
except:
    pass

try:
    net_cls = data['net_cls']
except:
    pass

os.system("/usr/lib64/lxcf/lxcf-resource1 cpun " + LXCNAME + " " + cpun)
os.system("/usr/lib64/lxcf/lxcf-resource1 cpurate " + LXCNAME + " "
          + cpurate)
os.system("/usr/lib64/lxcf/lxcf-resource1 numa " + LXCNAME + " " + numa)
os.system("/usr/lib64/lxcf/lxcf-resource1 memlimit " + LXCNAME + " "
          + memlimit)
os.system("/usr/lib64/lxcf/lxcf-resource1 memswlimit " + LXCNAME + " "
          + memswlimit)
for val in blkio_r:
    os.system("/usr/lib64/lxcf/lxcf-resource1 blkio_r " + LXCNAME + " "
              + blkio_val(val))
for val in blkio_w:
    os.system("/usr/lib64/lxcf/lxcf-resource1 blkio_w " + LXCNAME + " "
              + blkio_val(val))
for val in blkiops_r:
    os.system("/usr/lib64/lxcf/lxcf-resource1 blkiops_r " + LXCNAME + " "
              + blkio_val(val))
for val in blkiops_w:
    os.system("/usr/lib64/lxcf/lxcf-resource1 blkiops_w " + LXCNAME + " "
              + blkio_val(val))
os.system("/usr/lib64/lxcf/lxcf-resource1 net_cls " + LXCNAME + " "
          + net_cls)

sys.exit(0)
