def print_types(server):
	parsing.server_header(server,200)
	try:
		f = create_vm.fname
		fopen = open(f)
		server.wfile.write(parsing.json_out(json.load(fopen)))
	except Exception,e:
		print str(e)
		server.wfile.write(parsing.json_out({"status":0}))
def destroy(server,attributes):
	parsing.server_header(server,attributes)
	try:
		vmid = int(attributes[0])
		print "Deleting virtual machine with id",vmid
		print "iski pm::",parsing.vm_ki_info[vmid][2]
		v_name = parsing.vm_ki_info[vmid][0]
		machine_id = parsing.vm_ki_info[vmid][2]

		iski_pm = parsing.mac_user_ip[machine_id]
		iski_pm_add = iski_pm[0]+'@'+iski_pm[1]
		
		path = 'remote+ssh://'+iski_pm_add+'/system'
		print "Delete from machine ::",path
		connection = libvirt.open(path)
		try:
			r = connection.lookupByName(v_name)
		except:
			print "The said virtual machine does not exist on any physical machine."

		pp=parsing.vm_ki_info[vmid][3]			#store VM vs Phy machine details..
		iske_pm_ki_id=parsing.vm_ki_info[vmid][2]			#store VM vs Phy machine details..
		print "vm_type=====",pp
		print "cpu",parsing.free_resources[iske_pm_ki_id][0],create_vm.types_info[pp-1][1]
		print "ram",parsing.free_resources[iske_pm_ki_id][1],create_vm.types_info[pp-1][2]
		print "disk",parsing.free_resources[iske_pm_ki_id][2],create_vm.types_info[pp-1][3]
		
		parsing.free_resources[iske_pm_ki_id][0]+=create_vm.types_info[pp-1][1]
		parsing.free_resources[iske_pm_ki_id][1]+=create_vm.types_info[pp-1][2]
		parsing.free_resources[iske_pm_ki_id][2]+=create_vm.types_info[pp-1][3]
		#free_resources[iske_pm_ki_id][2]*1024/test_number+=types_info[pp-1][3]


		
		if r.isActive():
			r.destroy()
		r.undefine()

		print "capacity::",parsing.capacity_resources
		print "deleting now::",create_vm.types_info[pp-1]
		print "free::",parsing.free_resources


		del parsing.vm_ki_info[vmid]

		

		print "VM is Deleted an undefined"

		server.wfile.write(parsing.json_out({"status":1}))
	except:
		server.wfile.write(parsing.json_out({"status":0}))
def destroy(server,args):
	#global VOLUME_LIST
	print create_volume.VOLUME_LIST
	volume_id = int(args[0])
	if volume_id in create_volume.VOLUME_LIST:
		volume_name=str(create_volume.VOLUME_LIST[int(volume_id)])
	else:
		print "here\n"
		server.wfile.write(parsing.json_out({"status":0}))
	os.system('sudo rbd unmap /dev/rbd/%s/%s'%(main_file.POOL_NAME,volume_name))
	main_file.rbdInstance.remove(main_file.ioctx,volume_name)
	del create_volume.VOLUME_LIST[int(volume_id)]
	server.wfile.write(parsing.json_out({"status":1}))
def vm_query(server,attributes):
	parsing.server_header(server,attributes)
	try:
		vmid = int(attributes)
		print "Details of virtual machine with id",vmid
		v_name = parsing.vm_ki_info[vmid][0]
		machine_id = parsing.vm_ki_info[vmid][2]
		mtype = parsing.vm_ki_info[vmid][3]
		print "{vmid:",vmid,", name: ",v_name,"instance_type: ",machine_id,"pmid: ",mtype
		server.wfile.write(parsing.json_out({"vmid":vmid, "name":v_name, "instance_type": mtype, "pmid": machine_id}))
	except Exception,e:
		print str(e)
		server.wfile.write(parsing.json_out({"status":0}))
def create(server, args):
    global VOLUME_LIST
    volume_name = args[0]
    volume_size = args[1]
    actual_size = int(float(volume_size) * (1024 ** 2))
    try:
        main_file.rbdInstance.create(main_file.ioctx, str(volume_name), actual_size)
        os.system("sudo rbd map %s --pool %s --name client.admin" % (str(volume_name), str(main_file.POOL_NAME)))
        volume_id = vol_id
        vol_id = vol_id + 1
        VOLUME_LIST[vol_id] = str(volume_name)
        VOL_size[vol_id] = actual_size
        VOL_status[vol_id] = 0
        print VOLUME_LIST
        server.wfile.write(parsing.json_out({"volumeid": volume_id}))
    except:
        server.wfile.write(parsing.json_out({"volumeid": 0}))
def print_images(server):		#images list
	parsing.server_header(server,200)
	print_image = []
	image = []
	for keys in parsing.image_info:
		image = [keys,parsing.image_info[keys][1]]
		print_image.append(image)
	server.wfile.write(parsing.json_out({"images":print_image}))	
	pass
def volume_query(server,attributes):
	parsing.server_header(server,attributes)
	try:
		vmid=(int)attributes
		print "Details of Volumes with id",vmid
		v_name = create_volume.VOLUME_LIST[vmid]
		v_size = create_volume.VOL_size[vmid]
		v_status = create_volume.VOL_status[vmid]
		if v_status==0:
			print "{volumeid:",vmid,", name: ",v_name,"size: ",v_size,"status: available"
			server.wfile.write(parsing.json_out({"vmid":vmid, "name":v_name, "size: ",v_size,"status: available"}))
		elif v_status==1:
			print "error : It is deleted"
			server.wfile.write(parsing.json_out({"error:does not exist":vmid}))
		elif v_status>1 :
			print "{vmid:",vmid,", name: ",v_name,"size: ",v_size,"status: attached","vmid :",v_status
			server.wfile.write(parsing.json_out({"vmid":vmid, "name":v_name, "size: ",v_size,"status: attached","vmid :",v_status}))

	except Exception,e:
		print str(e)
		print "error : It does not exist"
		server.wfile.write(parsing.json_out({"error:does not exist":vmid}))
		server.wfile.write(parsing.json_out({"status":0}))
def create(server,args):
	parsing.server_header(server,args)
	if(1):
		vm_name = str(args[0])						# name of vm
		vm_type = int(args[1])						# tid of vm
		image_type = int(args[2])					# vm id
		type_properties = types_info[vm_type-1]  		## from types file, requirements of Virtual Machine
		images_list = parsing.image_info[image_type]  #dictionary
		
		i_name=images_list[1][0]
		h=0
		if "_64" in i_name:
			h=64
		else:
			h=32

		m,avai_pm_id = find_machine(type_properties,h)			# Get the physical machine to host the VM

		if avai_pm_id == 0:
			print "capacity::",parsing.capacity_resources
			print "In need of now::",type_properties
			print "free::",parsing.free_resources
			print "NO MACHINES AVAILABLE FOR THE TASK"
			return
		print "Machine id",avai_pm_id,"selected"
		machine_addr = m[0]+'@'+m[1]

		images_list = parsing.image_info[image_type]  #dictionary
		location_user = images_list[0][0]+'@'+images_list[0][1]
		location_image = images_list[2]			#Find the location of image
		
		print "images_list",images_list
		print "where",location_user
		print "what",location_image
		print "image_name",images_list[1][0]
		namefile=images_list[1][0]
		user_loc=m[0]+"@"+m[1]
		print "user is"+"./"+images_list[1][0]
		print "where to ?"+':'.join([user_loc,"/home/"+m[0]+"/Desktop"])

		if not os.path.isfile('./'+images_list[1][0]):
#			p = subprocess.Popen(["ssh",location_user])
			print machine_addr,location_image
			try:
				print "command run:: loc to you::scp",':'.join([location_user,images_list[2]]),"."
				subprocess.call(["scp",':'.join([location_user,images_list[2]]),"."])
				
				#subprocess.call(["scp",location_user+images_list[2]," ."])
			except:
				print "not able to scp to your machine"
		try:
			print "command run :: ur to user ::scp","./"+images_list[1][0],':'.join([user_loc,"/home/"+m[0]])
			subprocess.call(["scp","./"+images_list[1][0],':'.join([user_loc,"/home/"+m[0]+"/Desktop"])])
			
			#subprocess.call(["scp","./"+images_list[1][0],m[0]+"@"+m[1]+":/home/"+m[0]])
		except:
			print "not able to scp to user's machine"
				
			#print "scp",':'.join([location_user,location_image]),':'.join([machine_addr,'/var/lib/libvirt/images/'+images_list[1][0]])
#			p.kill()
		#subprocess.call(["scp",':'.join([location_user,location_image]),'/var/lib/libvirt/images/'])



		path = 'remote+ssh://'+m[0]+'@'+m[1]+'/system'
		print "Ssh to machine location::",path
		try:
			connection = libvirt.open(path)
		except:
			print "Could Not Open Connection\n"
			return

		system_info = connection.getCapabilities()	#get PM capabilities
		node_info = connection.getInfo()
		print "HERE I AM",node_info[1],node_info[2]
		emulator_path = system_info.split("emulator>")
		
		emulator_path = emulator_path[1].split("<")[0]	#location of xen/qemu
		
		emulator1 = system_info.split("<domain type=")
	
		emulator1 = emulator1[1].split(">")[0]		#emulator present xen/qemu
		
		arch_type = system_info.split("<arch>")
		arch_type = arch_type[1].split("<")[0]

		parsing.pm_capabilities[avai_pm_id] = [emulator_path ,emulator1, arch_type] #machine id as key--- stores physical machine arch details
#		print emulator_path ,emulator1, arch_type
		arch = parsing.pm_capabilities[avai_pm_id]

		hyper_type = connection.getType().lower()
		print "QEMU ?? or XEN??",hyper_type
		#type_properties[2] = (type_properties[2]*test_number)/1024

		#xml = create_xml(vm_name, type_properties,"/home/chitra/Downloads/Vm-linux.img",hyper_type,image_type,arch)  ## type_properties has tid,cpu,ram,disk
		xml = create_xml(vm_name, type_properties,"/home/"+m[0]+"/Desktop/"+images_list[1][0],hyper_type,image_type,arch)  ## type_properties has tid,cpu,ram,disk
#		print xml
	
		connect_xml = connection.defineXML(xml)
		try:
			connect_xml.create()
			print "********************** CREATED A VM :D *********************" 
			vmachine_id = parsing.get_id_for_vm(avai_pm_id)	#Get Virtual Machine unique ID -- avai_pm_id is machineid!
			parsing.vm_ki_info[vmachine_id] = [vm_name, type_properties, avai_pm_id,vm_type]			#store VM vs Phy machine details..

#			print "Here are details",parsing.vm_ki_info,vmachine_id
			server.wfile.write(parsing.json_out({"vmid":vmachine_id}))
			parsing.free_resources[avai_pm_id][0] -= type_properties[1]
			parsing.free_resources[avai_pm_id][1] -= type_properties[2]
			parsing.free_resources[avai_pm_id][2] -= type_properties[3]
			#type_properties[2] = (type_properties[2]*1024)/test_number
			
			#types_info[vm_type-1][2]=types_info[vm_type-1][2]*1024/test_number
		except Exception,e:
			#type_properties[2] = (type_properties[2]*1024)/test_number
			#parsing.free_resources[avai_pm_id][0] += type_properties[1]
			#parsing.free_resources[avai_pm_id][1] += type_properties[2]
			#parsing.free_resources[avai_pm_id][2] += type_properties[3]		
			
			print str(e)
			server.wfile.write(parsing.json_out({"vmid":0}))


		print "capacity::",parsing.capacity_resources
		print "using now::",type_properties
		print "free::",parsing.free_resources
			#type_properties[2] = (type_properties[2]*1024)/test_number
			#parsing.free_resources[avai_pm_id][0] += type_properties[1]
			#parsing.free_resources[avai_pm_id][1] += type_properties[2]
			#parsing.free_resources[avai_pm_id][2] += type_properties[3]		
			
			print str(e)
			server.wfile.write(parsing.json_out({"vmid":0}))


		print "capacity::",parsing.capacity_resources
		print "using now::",type_properties
		print "free::",parsing.free_resources
		

	else:
		server.wfile.write(parsing.json_out({"vmid":0}))
	
	
def parse_types(ff):
	f=open(ff,'r')
	global types_info
	global fname
	fname=ff
	f = open(ff)
	Typefile = json.load(f)
	print Typefile
	Typefile = Typefile['types']
	for x in Typefile:
		l = []
		for y in x:
			l.append(x[y])