#!/usr/bin/python -u
import os
import xenprototypeModulesCarrier
from xenprototype.VirtualManagementLib.virtualManagement import PhysicalHost
from xenprototype.CpuAllocation.cpuFeedbackControl import *
from xenprototype.CpuAllocation.throughputTest import *
from xenprototype.CpuAllocation.statistics import *

#This test is done with a stress of 10% in a virtual machine with controller off (cap set in 15%) and controller on (to limit in 20000kb/s)

testName = "WithDisturbance"

rounds = 10
count = 1
prefix = "eXpErImEnT"
testName = prefix + testName

os.popen("rm " + str(testName) + "*")

domainID = 1

while (count <= rounds):

	os.popen("killall iperf")

	#Perform the experiment using Controller Off

	physicalHost = PhysicalHost("floresta","xen+ssh")
	physicalHost.setSchedParametersCap(14,domainID)
	physicalHost.printSchedParameters()

	test1 = IperfTest(100,1,64,51200,"10.0.1.3",str(str(testName) + "OffVM1_" + str(count)),"146.164.69.149","5001")

	IperfThread("1",test1).start()


	while (test1.done == False):
		os.popen("sleep 1")

	averageThroughputList=[]

	os.popen("sleep 5")

	#Compute statistics for VM1	

	statistic = Statistics(str(str(testName) + "OffVM1_" + str(count)),20)
	output = open(str(testName + "Average"),'a')
	output.write("1 " + str(statistic.average) + "\n")
	output.close()
	output = open(str(testName + "RMSE"),'a')
	output.write("1 " + str(statistic.rmse) + "\n")
	output.close()	


	averageThroughputList.append(statistic.average)

	del statistic
	del test1
	del physicalHost

	#Perform the experiment using Controller On

	test1 = IperfTest(100,1,64,51200,"10.0.1.3",str(str(testName) + "OnVM1_" + str(count)),"146.164.69.149","5001")

	physicalHost = PhysicalHost("floresta","xen+ssh")

	samplePeriod = 1
	errorPercentageAcceptable = 0.1
	minPercentageSamplePeriod = 1
	constantCap = 0

	#Settings for VM1

	kp=float(-0.000003422)
	ki=float(0.000010158)
	desiredThroughput = 20000
	operationalPointThroughput = 40007

	control1 = ThroughputControl(desiredThroughput,1,physicalHost,test1,False)

	ControlThread("10001",control1).start()

	while (control1.done == "False"):
		os.popen("sleep 1")

	averageThroughputList=[]

	os.popen("sleep 5")

	#Compute statistics for VM1	

	statistic = Statistics(str(str(testName) + "OnVM1_" + str(count)),20)
	output = open(str(testName + "Average"),'a')
	output.write("2 " + str(statistic.average) + "\n")
	output.close()
	output = open(str(testName + "RMSE"),'a')
	output.write("2 " + str(statistic.rmse) + "\n")
	output.close()	

	averageThroughputList.append(statistic.average)
	del statistic
	del test1
	del physicalHost
	del control1

	print "Done " + str(count)
	count = count + 1
