Ejemplo n.º 1
0
def createVM():

	instance_type=int(request.args.get('instance_type'));
	image_id=int(request.args.get('image_id'))
	machineDetails=selectMachine(instance_type,image_id)

	if len(machineDetails)==5:
		name=request.args.get('name')
		imageDetails=query_db('select * from images where iid=?',[image_id], one=True);
		imageBit=32;
		imageName=str('.'.join(imageDetails[1].split('/')[-1].split('.')[0:-1]).strip('\n\r'));
		if imageName[-3:]=='_64':
			imageBit=64
		imageExt=str(imageDetails[1].split('/')[-1].split('.')[-1].strip('\n\r'))
		clientCount=query_db('select count(*) from clients')[0][0];
		clientCount=clientCount+1;
		print clientCount
		instance_type=query_db('select * from vmTypes where tid=?',[instance_type]);
		instance_type=instance_type[0]
		cpu=instance_type[1]
		ram=instance_type[2]
		disk=instance_type[3]
		#copy image from imageDetails[1] to machiceDetails[1] with name clientCount append clientCount at the end of all for uniqueness
		print imageDetails[1]
		print machineDetails[1]
		print imageName+str(clientCount)+'.'+imageExt
		imagePath=str("/")+str(imageName)+str(clientCount)+str(".")+str(imageExt)
		print imagePath
		print "-----------------"
		cmd=str("scp ")+str(imageDetails[1].strip('\n\r'))+str(" ")+str(machineDetails[1])+str(":/")+str(imageName)+str(clientCount)+str(".")+str(imageExt)
		print cmd
		print type(cmd)
		imageCopy=os.popen(cmd).read()
		print machineDetails[1]
		print "-----------------"
		print imageCopy
		
		#create vm if no error else retun 0
		vmid = col.createVM(imagePath,name,ram,cpu,machineDetails[4],machineDetails[1],imageBit)
		print vmid

		if vmid!=-1:
       	        	db = get_db()
			print name,image_id
                	db.execute('''insert into clients (vmid,name,vtid,mid,count) values (?,?,?,?,?)''',[int(vmid),str(name),int(instance_type[0]),int(machineDetails[0]),0])
			db.commit()
			db.execute('''update machines set ram=?,cpu=? where mid=?''',[machineDetails[2],machineDetails[3],machineDetails[0]]);
			db.commit()
			cid=query_db('select cid from clients')[-1];
			vmInfo = {'vmid':cid[0]}
			return jsonify(vmInfo)
		else:
			print 'error'
			vmInfo = {'vmid': 0}
			return jsonify(vmInfo)
	else:
		print 'error'
		vmInfo = {'vmid': 0}
		return jsonify(vmInfo)