Beispiel #1
0
def list_vms(request, server_id):

	if (not request.user.is_superuser):
        
		return simple.direct_to_template(request,
						template = 'not_admin.html',
						extra_context = {'user':request.user},
					)
	vmProjects = {}
	vmSlices = {}
	try:
		for vm in VTDriver.getVMsInServer(VTDriver.getServerById(server_id)):
			if vm.projectName not in vmProjects:
				vmProjects[vm.projectName] = vm.projectId
			if vm.sliceName not in vmSlices:
				vmSlices[vm.sliceName] = vm.sliceId
	except Exception as e:
		print e
		pass

	server = get_object_or_404(VTServer, pk=server_id)
			
	context = { 'vmProjects': vmProjects, 'vmSlices': vmSlices,'server':server}

	return simple.direct_to_template(
		request,
		template="servers/servers_list_vms.html",
		extra_context=context,
	)
Beispiel #2
0
def action_vm(request, server_id, vm_id, action):
	if (not request.user.is_superuser):
        
		return simple.direct_to_template(request,
			template = 'not_admin.html',
			extra_context = {'user':request.user},
		)

	if(action == 'list'):
          
		return simple.direct_to_template(
				request, template="servers/server_vm_details.html",
				extra_context={"vm": VTDriver.getVMbyId(vm_id), "server_id":server_id}
		)

	elif(action == 'check_status'):
		#XXX: Do this function if needed
		return simple.direct_to_template(
				request, template="servers/list_vm.html",
				extra_context={"vm": VM.objects.get(id = vm_id)}
		)
        elif(action == 'force_update_server'):
                InformationDispatcher.forceListActiveVMs(serverID=server_id)

        elif(action == 'force_update_vm'):
                InformationDispatcher.forceListActiveVMs(vmID=vm_id)
 
	else:
		#XXX: serverUUID should be passed in a different way
		VTDriver.PropagateActionToProvisioningDispatcher(vm_id, VTServer.objects.get(id=server_id).uuid, action)
    
	#return HttpResponseRedirect(reverse('edit_server', args = [server_id]))
	return HttpResponse("")
Beispiel #3
0
def delete_server(request, server_id):

	if (not request.user.is_superuser):
        
		return simple.direct_to_template(request,
				template = 'not_admin.html',
				extra_context = {'user':request.user},
		)
	if request.method == 'POST':
		try:
			VTDriver.deleteServer(VTDriver.getServerById(server_id))
			return HttpResponseRedirect(reverse('dashboard'))

		except Exception as e:
			logging.error(e)
			e = HttpUtils.processException(e)
			return simple.direct_to_template(request,
				template = 'servers/delete_server.html',
				extra_context = {'user':request.user, 'exception':e, 'next':reverse("admin_servers")},
				)	
	elif request.method == 'GET':
		return simple.direct_to_template(request,
				template = 'servers/delete_server.html',
				extra_context = {'user':request.user, 'next':reverse("admin_servers"),'object':VTDriver.getServerById(server_id)},
		)
Beispiel #4
0
def subscribeIp4Ranges(request, server_id):
    if (not request.user.is_superuser):
        return simple.direct_to_template(
            request,
            template='not_admin.html',
            extra_context={'user': request.user},
        )

    ipRanges = Ip4Range.objects.all()

    if server_id != None:
        server = get_object_or_404(VTServer, pk=server_id)
    else:
        raise Exception("NO SERVER")

    if request.method == "GET":
        return simple.direct_to_template(
            request,
            template='servers/servers_subscribeIp4Ranges.html',
            extra_context={
                'server': server,
                'ipRanges': ipRanges
            },
        )
    elif request.method == 'POST':
        VTDriver.manageIp4Ranges(request, server, ipRanges)
        return HttpResponseRedirect(reverse('edit_server', args=[server_id]))
    else:
        return HttpResponseNotAllowed("GET", "POST")
	def processResponse(rspec):
		logging.debug("PROCESSING RESPONSE proocessResponse() STARTED...")
		for action in rspec.response.provisioning.action:

			try:
				actionModel = ActionController.getAction(action.id)
			except Exception as e:
				logging.error("No action in DB with the incoming uuid\n%s", e)
				return

			'''
			If the response is for an action only in QUEUED or ONGOING status, SUCCESS or FAILED actions are finished
			'''

			if actionModel.getStatus() is Action.QUEUED_STATUS or Action.ONGOING_STATUS:
				logging.debug("The incoming response has id: %s and NEW status: %s",actionModel.uuid,actionModel.status)
				actionModel.status = action.status
				actionModel.description = action.description
				actionModel.save()
				#Complete information required for the Plugin: action type and VM
				ActionController.completeActionRspec(action, actionModel)

				#XXX:Implement this method or some other doing this job
				vm = VTDriver.getVMbyUUID(actionModel.getObjectUUID())
				controller=VTDriver.getDriver(vm.Server.get().getVirtTech())
				failedOnCreate = 0
				if actionModel.getStatus() == Action.SUCCESS_STATUS:
					ProvisioningResponseDispatcher.__updateVMafterSUCCESS(actionModel, vm)

				elif actionModel.getStatus() == Action.ONGOING_STATUS:
					ProvisioningResponseDispatcher.__updateVMafterONGOING(actionModel, vm)

				elif actionModel.getStatus() == Action.FAILED_STATUS:
					failedOnCreate = ProvisioningResponseDispatcher.__updateVMafterFAILED(actionModel, vm)

				else:
					vm.setState(VirtualMachine.UNKNOWN_STATE)


				try:
					logging.debug("Sending response to Plugin in sendAsync")
					XmlRpcClient.callRPCMethod(vm.getCallBackURL(), "sendAsync", XmlHelper.craftXmlClass(rspec))
					if failedOnCreate == 1:
						controller.deleteVM(vm)
				except Exception as e:
					logging.error("Could not connect to Plugin in sendAsync\n%s",e)
					return
			
			#If response is for a finished action
		
			else:
				try:
					#XXX: What should be done if this happen?
					logging.error("Received response for an action in wrong state\n")
					XmlRpcClient.callRPCMethod(vm.getCallBackURL(), "sendAsync", XmlHelper.getProcessingResponse(Action.ACTION_STATUS_FAILED_TYPE, action, "Received response for an action in wrong state"))
				except Exception as e:
					logging.error(e)
					return
 def forceListActiveVMs(serverID='None', vmID='None'):
     print serverID
     if serverID != 'None':
         server = VTDriver.getServerById(serverID)
         vms = server.getVMs()
     else:
         if vmID != 'None':
             servers = VTDriver.getAllServers()
             vms = list()
             for server in servers:
                 for vm in server.getVMs():
                     print vm.name, vm.id, int(vmID), type(
                         vm.id), vm.id == int(vmID)
                 vms = server.getVMs(id=int(vmID))
                 vmID = vms[0].getUUID()
                 break
             if not vms:
                 raise Exception("VM not Found")
     xmlrpc_server = xmlrpclib.Server(server.getAgentURL())
     vms_info = xmlrpc_server.force_list_active_vms(
         server.getAgentPassword(), vmID)
     updated_vms = list()
     simple_actions = dict()
     for vm in vms:
         if vm.getUUID() in vms_info.keys():
             vm.setState("running")
             vm.save()
             simple_actions[vm.getUUID()] = "running"
         else:
             if vm.getState() in [
                     'deleting...', 'failed', 'on queue', 'unknown'
             ]:
                 child = vm.getChildObject()
                 server = vm.Server.get()
                 #Action.objects.all().filter(objectUUID = vm.uuid).delete()
                 server.deleteVM(vm)
                 # Keep actions table up-to-date after each deletion
                 vm_uuids = [vm.uuid for vm in VirtualMachine.objects.all()]
                 Action.objects.all().exclude(
                     objectUUID__in=vm_uuids).delete()
                 simple_actions[vm.getUUID()] = "deleted"
             elif vm.getState() in [
                     'running', "starting...", "stopping..."
             ]:
                 vm.setState('stopped')
                 vm.save()
                 simple_actions[vm.getUUID()] = "stopped"
             else:
                 continue
     return vms_info
    def processProvisioning(provisioning):
		logging.debug("PROVISIONING STARTED...\n")
		for action in provisioning.action:
			actionModel = ActionController.ActionToModel(action,"provisioning")
			logging.debug("ACTION type: %s with id: %s" % (actionModel.type, actionModel.uuid))
			try:
				RuleTableManager.Evaluate(action,RuleTableManager.getDefaultName())
			except Exception as e:
				MAX_CHARS_ALLOWED = 200
				XmlRpcClient.callRPCMethod(threading.currentThread().callBackURL,"sendAsync",XmlHelper.craftXmlClass(XmlHelper.getProcessingResponse(Action.FAILED_STATUS, action,str(e)[0:MAX_CHARS_ALLOWED-1])))
				return None
			try:
				controller = VTDriver.getDriver(action.server.virtualization_type)
				#XXX:Change this when xml schema is updated
				server = VTDriver.getServerByUUID(action.server.uuid)
				#if actionModel.getType() == Action.PROVISIONING_VM_CREATE_TYPE:
				#	server = VTDriver.getServerByUUID(action.virtual_machine.server_id)
				#else:
				#	server = VTDriver.getVMbyUUID(action.virtual_machine.uuid).Server.get()
			except Exception as e:
				logging.error(e)
				raise e
			try:	
				#PROVISIONING CREATE
				if actionModel.getType() == Action.PROVISIONING_VM_CREATE_TYPE:
					try:
						vm = ProvisioningDispatcher.__createVM(controller, actionModel, action)
					except:
						vm = None
						raise
				#PROVISIONING DELETE, START, STOP, REBOOT
				else :
					ProvisioningDispatcher.__deleteStartStopRebootVM(controller, actionModel, action)
				XmlRpcClient.callRPCMethod(server.getAgentURL() ,"send", UrlUtils.getOwnCallbackURL(), 1, server.getAgentPassword(),XmlHelper.craftXmlClass(XmlHelper.getSimpleActionQuery(action)) )
				return
			except Exception as e:
				if actionModel.getType() == Action.PROVISIONING_VM_CREATE_TYPE:
					# If the VM creation was interrupted in the network
					# configuration, the created VM won't be returned
					try:
						if not vm:
							vm = controller.getVMbyUUID(action.server.virtual_machines[0].uuid)
						controller.deleteVM(vm)
						# Keep actions table up-to-date after each deletion
						actionModel.delete()
					except Exception as e:
						print "Could not delete VM. Exception: %s" % str(e)
				#XmlRpcClient.callRPCMethod(threading.currentThread().callBackURL,"sendAsync",XmlHelper.craftXmlClass(XmlHelper.getProcessingResponse(Action.FAILED_STATUS, action, str(e))))
		logging.debug("PROVISIONING FINISHED...")
    def processProvisioning(provisioning):
		logging.debug("PROVISIONING STARTED...\n")
		for action in provisioning.action:
			actionModel = ActionController.ActionToModel(action,"provisioning")
			logging.debug("ACTION type: %s with id: %s" % (actionModel.type, actionModel.uuid))
			try:
				RuleTableManager.Evaluate(action,RuleTableManager.getDefaultName())
			except Exception as e:
				MAX_CHARS_ALLOWED = 200
				XmlRpcClient.callRPCMethod(threading.currentThread().callBackURL,"sendAsync",XmlHelper.craftXmlClass(XmlHelper.getProcessingResponse(Action.FAILED_STATUS, action,str(e)[0:MAX_CHARS_ALLOWED-1])))
				return None
			try:
				controller = VTDriver.getDriver(action.server.virtualization_type)
				#XXX:Change this when xml schema is updated
				server = VTDriver.getServerByUUID(action.server.uuid)
				#if actionModel.getType() == Action.PROVISIONING_VM_CREATE_TYPE:
				#	server = VTDriver.getServerByUUID(action.virtual_machine.server_id)
				#else:
				#	server = VTDriver.getVMbyUUID(action.virtual_machine.uuid).Server.get()
			except Exception as e:
				logging.error(e)
				raise e
			try:	
				#PROVISIONING CREATE
				if actionModel.getType() == Action.PROVISIONING_VM_CREATE_TYPE:
					try:
						vm = ProvisioningDispatcher.__createVM(controller, actionModel, action)
					except:
						vm = None
						raise
				#PROVISIONING DELETE, START, STOP, REBOOT
				else :
					ProvisioningDispatcher.__deleteStartStopRebootVM(controller, actionModel, action)
				XmlRpcClient.callRPCMethod(server.getAgentURL() ,"send", UrlUtils.getOwnCallbackURL(), 1, server.getAgentPassword(),XmlHelper.craftXmlClass(XmlHelper.getSimpleActionQuery(action)) )
				return
			except Exception as e:
				if actionModel.getType() == Action.PROVISIONING_VM_CREATE_TYPE:
					# If the VM creation was interrupted in the network
					# configuration, the created VM won't be returned
					try:
						if not vm:
							vm = controller.getVMbyUUID(action.server.virtual_machines[0].uuid)
						controller.deleteVM(vm)
						# Keep actions table up-to-date after each deletion
						actionModel.delete()
					except Exception as e:
						print "Could not delete VM. Exception: %s" % str(e)
				#XmlRpcClient.callRPCMethod(threading.currentThread().callBackURL,"sendAsync",XmlHelper.craftXmlClass(XmlHelper.getProcessingResponse(Action.FAILED_STATUS, action, str(e))))
		logging.debug("PROVISIONING FINISHED...")
Beispiel #9
0
 def forceListActiveVMs(serverID='None', vmID='None'):
     if serverID != 'None':
         server = VTDriver.getServerById(serverID)
         vtam_vms = server.getVMs()
     else:
         if vmID != 'None':
             servers = VTDriver.getAllServers()
             vtam_vms = list()
             for server in servers:
                 vtam_vms = server.getVMs(id=int(vmID))
                 if vtam_vms:
                     vmID = vtam_vms[0].getUUID()
                     break
             if not vtam_vms:
                 raise Exception("VM not found")
     xmlrpc_server = xmlrpclib.Server(server.getAgentURL())
     # Handle safely the connection against the agent
     try:
         server_active_vms = xmlrpc_server.force_list_active_vms(
             server.getAgentPassword(), vmID)
         for vm in vtam_vms:
             if vm.getUUID() in server_active_vms.keys():
                 vm.setState("running")
                 vm.save()
             else:
                 # XXX: avoiding "on queue" and "unknown" states to avoid bad management
                 #if vm.getState() in ['deleting...', 'failed', 'on queue', 'unknown']:
                 if vm.getState() in ["deleting...", "failed"]:
                     child = vm.getChildObject()
                     server = vm.Server.get()
                     #Action.objects.all().filter(objectUUID = vm.uuid).delete()
                     server.deleteVM(vm)
                     # Keep actions table up-to-date after each deletion
                     vm_uuids = [
                         vm.uuid for vm in VirtualMachine.objects.all()
                     ]
                     Action.objects.all().exclude(
                         objectUUID__in=vm_uuids).delete()
                 elif vm.getState() in [
                         "running", "starting...", "stopping..."
                 ]:
                     vm.setState("stopped")
                     vm.save()
                 else:
                     continue
     except:
         server_active_vms = dict()
     return server_active_vms
Beispiel #10
0
 def __crudVM(self, server_uuid, vm_id, action):
     try:
         VTDriver.PropagateActionToProvisioningDispatcher(
             vm_id, server_uuid, action)
     except Exception as e:
         raise e
     return 1
	def listVMTemplatesInfo(serverUUID):
	#def listVMTemplatesInfo(serverUUID, callbackURL):
		logging.debug("Enter listVMTemplatesInfo")
		server = VTDriver.getServerByUUID(serverUUID)
		xmlrpc_server = xmlrpclib.Server(server.getAgentURL())
		templates_info = xmlrpc_server.list_vm_templates(server.getAgentPassword())
		#templates_info = xmlrpc_server.list_vm_templates(callbackURL, server.getAgentPassword())
		return str(templates_info)
 def listVMTemplatesInfo(serverUUID):
     #def listVMTemplatesInfo(serverUUID, callbackURL):
     logging.debug("Enter listVMTemplatesInfo")
     server = VTDriver.getServerByUUID(serverUUID)
     xmlrpc_server = xmlrpclib.Server(server.getAgentURL())
     templates_info = xmlrpc_server.list_vm_templates(
         server.getAgentPassword())
     #templates_info = xmlrpc_server.list_vm_templates(callbackURL, server.getAgentPassword())
     return str(templates_info)
 def forceListActiveVMs(serverID='None', vmID='None'):
         print serverID
         if serverID != 'None':
             server = VTDriver.getServerById(serverID)
             vms = server.getVMs()
         else: 
             if vmID != 'None':
                 servers = VTDriver.getAllServers()
                 vms = list()
                 for server in servers:
                     for vm in server.getVMs():
                         print vm.name, vm.id, int(vmID), type(vm.id), vm.id==int(vmID)  
                     vms = server.getVMs(id=int(vmID))
                     vmID = vms[0].getUUID()
                     break
                 if not vms:
                     raise Exception("VM not Found")
         xmlrpc_server = xmlrpclib.Server(server.getAgentURL())
         vms_info = xmlrpc_server.force_list_active_vms(server.getAgentPassword(), vmID)
         updated_vms = list()
         simple_actions = dict() 
         for vm in vms:
             if vm.getUUID() in vms_info.keys():
                 vm.setState("running")
                 vm.save()
                 simple_actions[vm.getUUID()] = "running"
             else:
                 if vm.getState() in ['deleting...', 'failed', 'on queue', 'unknown']:
                     child = vm.getChildObject()
                     server = vm.Server.get()
                     #Action.objects.all().filter(objectUUID = vm.uuid).delete()
                     server.deleteVM(vm)
                     # Keep actions table up-to-date after each deletion
                     vm_uuids = [ vm.uuid for vm in VirtualMachine.objects.all() ]
                     Action.objects.all().exclude(objectUUID__in = vm_uuids).delete()
                     simple_actions[vm.getUUID()] = "deleted"
                 elif vm.getState() in ['running', "starting...", "stopping..."] :
                     vm.setState('stopped')
                     vm.save()
                     simple_actions[vm.getUUID()] = "stopped"
                 else:
                     continue
         return vms_info
	def __updateVMafterSUCCESS(actionModel, vm):
		if actionModel.getType() == Action.PROVISIONING_VM_CREATE_TYPE:
			vm.setState(VirtualMachine.CREATED_STATE)
		elif actionModel.getType() == Action.PROVISIONING_VM_START_TYPE or actionModel.getType() == Action.PROVISIONING_VM_REBOOT_TYPE:
			vm.setState(VirtualMachine.RUNNING_STATE)
		elif actionModel.getType() == Action.PROVISIONING_VM_STOP_TYPE:
			vm.setState(VirtualMachine.STOPPED_STATE)
		elif actionModel.getType() == Action.PROVISIONING_VM_DELETE_TYPE:
			controller = VTDriver.getDriver(vm.Server.get().getVirtTech())
			controller.deleteVM(vm)
Beispiel #15
0
 def forceListActiveVMs(serverID='None', vmID='None'):
         if serverID != 'None':
             server = VTDriver.getServerById(serverID)
             vtam_vms = server.getVMs()
         else: 
             if vmID != 'None':
                 servers = VTDriver.getAllServers()
                 vtam_vms = list()
                 for server in servers:
                     vtam_vms = server.getVMs(id=int(vmID))
                     if vtam_vms:
                         vmID = vtam_vms[0].getUUID()
                         break
                 if not vtam_vms:
                     raise Exception("VM not found")
         xmlrpc_server = xmlrpclib.Server(server.getAgentURL())
         # Handle safely the connection against the agent
         try:
             server_active_vms = xmlrpc_server.force_list_active_vms(server.getAgentPassword(), vmID)
             for vm in vtam_vms:
                 if vm.getUUID() in server_active_vms.keys():
                     vm.setState("running")
                     vm.save()
                 else:
                     # XXX: avoiding "on queue" and "unknown" states to avoid bad management
                     #if vm.getState() in ['deleting...', 'failed', 'on queue', 'unknown']:
                     if vm.getState() in ["deleting...", "failed"]:
                         child = vm.getChildObject()
                         server = vm.Server.get()
                         #Action.objects.all().filter(objectUUID = vm.uuid).delete()
                         server.deleteVM(vm)
                         # Keep actions table up-to-date after each deletion
                         vm_uuids = [ vm.uuid for vm in VirtualMachine.objects.all() ]
                         Action.objects.all().exclude(objectUUID__in = vm_uuids).delete()
                     elif vm.getState() in ["running", "starting...", "stopping..."] :
                         vm.setState("stopped")
                         vm.save()
                     else:
                         continue
         except:
             server_active_vms = dict()
         return server_active_vms
	def __updateVMafterSUCCESS(actionModel, vm):
		if actionModel.getType() == Action.PROVISIONING_VM_CREATE_TYPE:
			vm.setState(VirtualMachine.CREATED_STATE)
		elif actionModel.getType() == Action.PROVISIONING_VM_START_TYPE or actionModel.getType() == Action.PROVISIONING_VM_REBOOT_TYPE:
			vm.setState(VirtualMachine.RUNNING_STATE)
		elif actionModel.getType() == Action.PROVISIONING_VM_STOP_TYPE:
			vm.setState(VirtualMachine.STOPPED_STATE)
		elif actionModel.getType() == Action.PROVISIONING_VM_DELETE_TYPE:
			controller = VTDriver.getDriver(vm.Server.get().getVirtTech())
			controller.deleteVM(vm)
			# Keep actions table up-to-date after each deletion
			actionModel.delete()
	def listResources(remoteHashValue, projectUUID = 'None', sliceUUID ='None'):
		logging.debug("Enter listResources")
		infoRspec = XmlHelper.getSimpleInformation()
		servers = VTDriver.getAllServers()
		baseVM = copy.deepcopy(infoRspec.response.information.resources.server[0].virtual_machine[0])
		if not servers:
			logging.debug("No VTServers available")
			infoRspec.response.information.resources.server.pop()
			resourcesString = XmlHelper.craftXmlClass(infoRspec)
			localHashValue = str(hash(resourcesString))
		else:
			for sIndex, server in enumerate(servers):
				if(sIndex == 0):
					baseServer = copy.deepcopy(infoRspec.response.information.resources.server[0])
				if(sIndex != 0):
					newServer = copy.deepcopy(baseServer)
					infoRspec.response.information.resources.server.append(newServer)
	
				InformationDispatcher.__ServerModelToClass(server, infoRspec.response.information.resources.server[sIndex] )
				if (projectUUID is not 'None'):
					vms = server.getVMs(projectId = projectUUID)
				else:
					vms = server.getVMs()
				if not vms:
					logging.debug("No VMs available")
					if infoRspec.response.information.resources.server[sIndex].virtual_machine:
						infoRspec.response.information.resources.server[sIndex].virtual_machine.pop()
				elif (sliceUUID is not 'None'):
					vms = vms.filter(sliceId = sliceUUID)
					if not vms:
						logging.error("No VMs available")
						infoRspec.response.information.resources.server[sIndex].virtual_machine.pop()
				for vIndex, vm in enumerate(vms):
					if (vIndex != 0):
						newVM = copy.deepcopy(baseVM)
						infoRspec.response.information.resources.server[sIndex].virtual_machine.append(newVM)
					InformationDispatcher.__VMmodelToClass(vm, infoRspec.response.information.resources.server[sIndex].virtual_machine[vIndex])
	
			resourcesString =   XmlHelper.craftXmlClass(infoRspec)
			localHashValue = str(hash(resourcesString))
		try:
			rHashObject =  resourcesHash.objects.get(projectUUID = projectUUID, sliceUUID = sliceUUID)
			rHashObject.hashValue = localHashValue
			rHashObject.save()
		except:
			rHashObject = resourcesHash(hashValue = localHashValue, projectUUID= projectUUID, sliceUUID = sliceUUID)
			rHashObject.save()
	
		if remoteHashValue == rHashObject.hashValue:
			return localHashValue, ''
		else:
			return localHashValue, resourcesString
Beispiel #18
0
def admin_servers(request):
    
	if (not request.user.is_superuser):
        
		return simple.direct_to_template(request,
				template = 'not_admin.html',
				extra_context = {'user':request.user},
			) 
	
	servers = VTDriver.getAllServers()

	return simple.direct_to_template(
		request, template="servers/admin_servers.html",
		extra_context={"servers_ids": servers})
Beispiel #19
0
 def __crud_vm(self, urn, action):
     params = self.__urn_to_vm_params(urn)
     servers = VTServer.objects.all()
     vm_server_pairs = list()
     resources = list()
     for server in servers:
         vms = list()
         # Look for provisioned VMs
         vms_provisioned = server.getChildObject().getVMs(**params)
         # ... Also for reserved VMs
         vms_allocated = Reservation.objects.filter(server__id=server.id,
                                                    **params)
         vms.extend(vms_provisioned)
         vms.extend(vms_allocated)
         for vm in vms:
             # The following is to be executed only for provisioned VMs
             if isinstance(vm, VirtualMachine):
                 # Return "REFUSED" exception if sliver is in a transient state
                 self.__validate_precondition_states(vm, action)
                 # Return "BUSY" exception if sliver is in incorrect operational state
                 if self.__translate_to_operational_state(
                         vm) == self.GENI_UPDATING_USERS:
                     raise Exception("BUSY sliver in state '%s'" %
                                     self.GENI_UPDATING_USERS)
                 vm_params = {"server_uuid": server.uuid, "vm_id": vm.id}
                 if vm_params not in vm_server_pairs:
                     vm_server_pairs.append(vm_params)
                 try:
                     with self.__mutex_thread:
                         VTDriver.PropagateActionToProvisioningDispatcher(
                             vm.id, server.uuid, action)
                 except Exception as e:
                     try:
                         if self.get_geni_best_effort_mode():
                             resource = self.__convert_to_resources_with_slivers(
                                 server, [vm])[0]
                             resource.set_error_message(str(e))
                             #resources.extend(resource)
                             resources.append(resource)
                             continue
                         else:
                             raise e
                     except Exception as e:
                         raise e
             # The resources are fetched for any (allocated/provisioned) VM
             resource = self.__convert_to_resources_with_slivers(
                 server, [vm])
             resources.extend(resource)
     return resources
Beispiel #20
0
def subscribeIp4Ranges(request, server_id):
	if (not request.user.is_superuser):
		return simple.direct_to_template(request,
					template = 'not_admin.html',
					extra_context = {'user':request.user},
		)

	ipRanges = Ip4Range.objects.all()

	if server_id != None:
		server = get_object_or_404(VTServer, pk=server_id)
	else:
		raise Exception ("NO SERVER")
	
	if request.method == "GET":
		return simple.direct_to_template(request,
				template = 'servers/servers_subscribeIp4Ranges.html',
				extra_context = {'server': server, 'ipRanges':ipRanges},
		)
	elif request.method=='POST':
		VTDriver.manageIp4Ranges(request,server,ipRanges)
		return HttpResponseRedirect(reverse('edit_server', args = [server_id]))
	else:
		return HttpResponseNotAllowed("GET", "POST")
Beispiel #21
0
def dashboard(request):
	'''
	The dashboard view function
	'''
    
	if (not request.user.is_superuser):
		return HttpResponseRedirect('/accounts/login')        
   
	else: #Admin
        
		servers = VTDriver.getAllServers()
            
		return simple.direct_to_template(request, 
							template = 'dashboard_admin.html',
							extra_context = {
							'user': request.user,
							'servers' : servers,
							},
						)
 def processresponseSync(rspec):
     """
     Thread-free implementation.
     """
     logging.debug("PROCESSING RESPONSE processResponseSync() STARTED...")
     for action in rspec.response.provisioning.action:
         try:
             actionModel = ActionController.getAction(action.id)
         except Exception as e:
             logging.error("No action in DB with the incoming uuid\n%s", e)
             return
         
         """
         If the response is for an action only in QUEUED or ONGOING status, SUCCESS or FAILED actions are finished
         """
         #if str(actionModel.callBackUrl) == str(SfaCommunicator.SFAUrl): #Avoiding unicodes
         #       event = pull(str(action.id))
         #       event.send('continue')
         #       return
         
         logging.debug("................................ actionModel.getStatus(): %s ................." % str(actionModel.getStatus()))
         if actionModel.getStatus() is Action.QUEUED_STATUS or Action.ONGOING_STATUS:
             logging.debug("The incoming response has id: %s and NEW status: %s" % (actionModel.uuid,actionModel.status))
             actionModel.status = action.status
             actionModel.description = action.description
             actionModel.save()
             #Complete information required for the Plugin: action type and VM
             ActionController.completeActionRspec(action, actionModel)
             
             #XXX:Implement this method or some other doing this job
             vm = VTDriver.getVMbyUUID(actionModel.getObjectUUID())
             controller = VTDriver.getDriver(vm.Server.get().getVirtTech())
             failedOnCreate = 0
             if actionModel.getStatus() == Action.SUCCESS_STATUS:
                 ProvisioningResponseDispatcher.__updateVMafterSUCCESS(actionModel, vm)
             elif actionModel.getStatus() == Action.ONGOING_STATUS:
                 ProvisioningResponseDispatcher.__updateVMafterONGOING(actionModel, vm)
             elif actionModel.getStatus() == Action.FAILED_STATUS:
                 failedOnCreate = ProvisioningResponseDispatcher.__updateVMafterFAILED(actionModel, vm)
             else:
                 vm.setState(VirtualMachine.UNKNOWN_STATE)
             
             try:
                 logging.debug("Sending response to Plugin in sendAsync")
                 if str(actionModel.callBackUrl) == 'SFA.OCF.VTM':
                     logging.debug(">>>>>>> SFA.OCF.VTM\n\n\n")
                     if failedOnCreate:
                         logging.debug("........... failedOnCreate.........")
                         expiring_slices = vm.objects.filter(sliceName=vm.sliceName,projectName=vm.projectName)
                         logging.debug("........... expiring_slices: %s ..........." % str(expiring_slices))
                         if len(expiring_slices)  == 1:
                             expiring_slices[0].delete()
                 
                 # Cleaning up reservation objects
                 ProvisioningResponseDispatcher.__clean_up_reservations(vm.name)
                 
                 XmlRpcClient.callRPCMethod(vm.getCallBackURL(), "sendSync", XmlHelper.craftXmlClass(rspec))
                 if failedOnCreate == 1:
                     controller.deleteVM(vm)
                     # Keep actions table up-to-date after each deletion
                     actionModel.delete()
             except Exception as e:
                 logging.error("Could not connect to Plugin in sendSync. Exception: %s",e)
                 return
     
         # If response is for a finished action
         else:
             try:
                 #XXX: What should be done if this happen?
                 logging.error("Received response for an action in wrong state")
                 XmlRpcClient.callRPCMethod(vm.getCallBackURL(), "sendSync", XmlHelper.getProcessingResponse(Action.ACTION_STATUS_FAILED_TYPE, action, "Received response for an action in wrong state"))
             except Exception as e:
                 logging.error(e)
                 return
Beispiel #23
0
def servers_crud(request, server_id=None):

	"""Show a page for the user to add/edit an  VTServer """

	if (not request.user.is_superuser):
        
		return simple.direct_to_template(request,
						template = 'not_admin.html',
						extra_context = {'user':request.user},
					)
	vmProjects = {}
	vmSlices = {}
	try:
		for vm in VTDriver.getVMsInServer(VTDriver.getServerById(server_id)):
			if vm.projectName not in vmProjects:
				vmProjects[vm.projectName] = vm.projectId
			if vm.sliceName not in vmSlices:
				vmSlices[vm.sliceName] = vm.sliceId
	except Exception as e:
		print e
		pass
	
	serverFormClass = HttpUtils.getFormFromModel(VTServer)
	ifaceFormClass = HttpUtils.getFormFromModel(NetworkInterface)
	IfaceFormSetClass = modelformset_factory(NetworkInterface)

	if server_id != None:
		server = get_object_or_404(VTServer, pk=server_id)
	else:
		server = None
	
	if request.method == "GET":
		#serverForm = serverFormClass(instance=server)
		serverForm = ServerForm(instance=server, prefix ="server")

		if server != None:
			mgmt = server.getNetworkInterfaces().filter(isMgmt = True)
			if mgmt:
				mgmt = mgmt.get()
				mgmtIfaceForm = MgmtBridgeForm({'mgmtBridge-name':mgmt.getName(), 'mgmtBridge-mac':mgmt.getMacStr()}, prefix ="mgmtBridge")
			else:
				mgmtIfaceForm = MgmtBridgeForm(prefix ="mgmtBridge")
			
			data = server.getNetworkInterfaces().filter(isMgmt = False)
			if data:
				IfaceFormSetClass = modelformset_factory(NetworkInterface,extra = 0)
			ifaceformset = IfaceFormSetClass(queryset= data)

		else:
			mgmtIfaceForm = MgmtBridgeForm(prefix ="mgmtBridge")
			ifaceformset = IfaceFormSetClass(queryset= NetworkInterface.objects.none())
			
	elif request.method == "POST":
		#serverForm = serverFormClass(request.POST, instance=server)
		serverForm = ServerForm(request.POST, instance=server, prefix ="server")
		ifaceformset = IfaceFormSetClass(request.POST)
		mgmtIfaceForm = MgmtBridgeForm(request.POST, prefix ="mgmtBridge")
		
		if serverForm.is_valid() and ifaceformset.is_valid() and mgmtIfaceForm.is_valid():
			ifaces = ifaceformset.save(commit = False)
			if server == None:
				server = serverForm.save(commit = False)
			try:
				server = VTDriver.crudServerFromInstance(server)
				VTDriver.setMgmtBridge(request, server)
				VTDriver.crudDataBridgeFromInstance(server, ifaces,request.POST.getlist("DELETE"))
			except Exception as e:
				print e
				e = HttpUtils.processException(e)	
				context = {"exception":e, "serverForm": serverForm, 'vmProjects': vmProjects, 'vmSlices': vmSlices,'ifaceformset' : ifaceformset, 'mgmtIfaceForm' : mgmtIfaceForm}
				if server_id != None: context["server"] = server
				return simple.direct_to_template(
				        request,
				        template="servers/servers_crud.html",
				        extra_context=context,
				    )

			# Returns to server's admin page and rollback transactions
			return HttpResponseRedirect('/servers/admin/')
	else:
		return HttpResponseNotAllowed("GET", "POST")

	context = {"serverForm": serverForm, 'vmProjects': vmProjects, 'vmSlices': vmSlices,'ifaceformset' : ifaceformset, 'mgmtIfaceForm' : mgmtIfaceForm}
	if server_id != None: context["server"] = server

	return simple.direct_to_template(
		request,
		template="servers/servers_crud.html",
		extra_context=context,
	)
Beispiel #24
0
    def processResponse(rspec):
        logging.debug("PROCESSING RESPONSE processResponse() STARTED...")
        for action in rspec.response.provisioning.action:
            try:
                actionModel = ActionController.getAction(action.id)
            except Exception as e:
                logging.error("No action in DB with the incoming uuid\n%s", e)
                return
            '''
			If the response is for an action only in QUEUED or ONGOING status, SUCCESS or FAILED actions are finished
			'''
            #if str(actionModel.callBackUrl) == str(SfaCommunicator.SFAUrl): #Avoiding unicodes
            #	event = pull(str(action.id))
            #	event.send('continue')
            #	return

            if actionModel.getStatus(
            ) is Action.QUEUED_STATUS or Action.ONGOING_STATUS:
                logging.debug(
                    "The incoming response has id: %s and NEW status: %s" %
                    (actionModel.uuid, actionModel.status))
                was_creating = False
                was_created = False
                actionModel.status = action.status
                actionModel.description = action.description
                actionModel.save()
                #Complete information required for the Plugin: action type and VM
                ActionController.completeActionRspec(action, actionModel)

                #XXX:Implement this method or some other doing this job
                vm = VTDriver.getVMbyUUID(actionModel.getObjectUUID())
                if vm.state == "creating...":
                    was_creating = True
                elif vm.state == "starting...":
                    was_created = True
                controller = VTDriver.getDriver(vm.Server.get().getVirtTech())
                failedOnCreate = 0
                # Update VM model with new status from OXAD
                if actionModel.getStatus() == Action.SUCCESS_STATUS:
                    ProvisioningResponseDispatcher.__updateVMafterSUCCESS(
                        actionModel, vm)
                elif actionModel.getStatus() == Action.ONGOING_STATUS:
                    ProvisioningResponseDispatcher.__updateVMafterONGOING(
                        actionModel, vm)
                elif actionModel.getStatus() == Action.FAILED_STATUS:
                    failedOnCreate = ProvisioningResponseDispatcher.__updateVMafterFAILED(
                        actionModel, vm)
                else:
                    vm.setState(VirtualMachine.UNKNOWN_STATE)
                try:
                    created = False
                    vm_started = False
                    if vm.state == "created (stopped)":
                        created = True
                    elif vm.state == "running":
                        vm_started = True
                    logging.debug("Sending response to plug-in in sendAsync")
                    if str(vm.callBackURL) == 'SFA.OCF.VTM':
                        logging.debug("callback: %s" % vm.callBackURL)
                        print "-------------->PRD: Created:", created, "Was_creating:", was_creating, "vm_started:", vm_started
                        print "-------------->PRD Action:", action, action.server.__dict__
                        # Start VM just after creating sliver/VM
                        if created and was_creating:
                            from vt_manager.communication.sfa.drivers.VTSfaDriver import VTSfaDriver
                            driver = VTSfaDriver(None)
                            driver.crud_slice(vm.sliceName, vm.projectName,
                                              "start_slice")
                            ProvisioningResponseDispatcher.__clean_up_reservations(
                                vm.uuid)
                            return
                        #if was_created and vm_started:
                        if vm_started:
                            ifaces = vm.getNetworkInterfaces()
                            for iface in ifaces:
                                if iface.isMgmt:
                                    ip = iface.ip4s.all()[0].ip

                            # Contextualize VMs
                            ProvisioningResponseDispatcher.__contextualize_vm(
                                vm, ip)
                            # Cleaning up reservation objects
                        return
                    XmlRpcClient.callRPCMethod(vm.getCallBackURL(),
                                               "sendAsync",
                                               XmlHelper.craftXmlClass(rspec))
                    if failedOnCreate == 1:
                        controller.deleteVM(vm)
                        # Keep actions table up-to-date after each deletion
                        actionModel.delete()
                except Exception as e:
                    logging.error(
                        "Could not connect to Plugin in sendAsync\n%s", e)
                    return

            #If response is for a finished action
            else:
                try:
                    #XXX: What should be done if this happen?
                    logging.error(
                        "Received response for an action in wrong state\n")
                    XmlRpcClient.callRPCMethod(
                        vm.getCallBackURL(), "sendAsync",
                        XmlHelper.getProcessingResponse(
                            Action.ACTION_STATUS_FAILED_TYPE, action,
                            "Received response for an action in wrong state"))
                except Exception as e:
                    logging.error(e)
                    return
Beispiel #25
0
    def processresponseSync(rspec):
        """
            Thread-free implementation.
            """
        logging.debug("PROCESSING RESPONSE processResponseSync() STARTED...")
        for action in rspec.response.provisioning.action:
            try:
                actionModel = ActionController.getAction(action.id)
            except Exception as e:
                logging.error("No action in DB with the incoming uuid\n%s", e)
                return
            """
                If the response is for an action only in QUEUED or ONGOING status, SUCCESS or FAILED actions are finished
                """
            #if str(actionModel.callBackUrl) == str(SfaCommunicator.SFAUrl): #Avoiding unicodes
            #       event = pull(str(action.id))
            #       event.send('continue')
            #       return

            logging.debug(
                "................................ actionModel.getStatus(): %s ................."
                % str(actionModel.getStatus()))
            if actionModel.getStatus(
            ) is Action.QUEUED_STATUS or Action.ONGOING_STATUS:
                logging.debug(
                    "The incoming response has id: %s and NEW status: %s" %
                    (actionModel.uuid, actionModel.status))
                actionModel.status = action.status
                actionModel.description = action.description
                actionModel.save()
                #Complete information required for the Plugin: action type and VM
                ActionController.completeActionRspec(action, actionModel)

                #XXX:Implement this method or some other doing this job
                vm = VTDriver.getVMbyUUID(actionModel.getObjectUUID())
                controller = VTDriver.getDriver(vm.Server.get().getVirtTech())
                failedOnCreate = 0
                if actionModel.getStatus() == Action.SUCCESS_STATUS:
                    ProvisioningResponseDispatcher.__updateVMafterSUCCESS(
                        actionModel, vm)
                elif actionModel.getStatus() == Action.ONGOING_STATUS:
                    ProvisioningResponseDispatcher.__updateVMafterONGOING(
                        actionModel, vm)
                elif actionModel.getStatus() == Action.FAILED_STATUS:
                    failedOnCreate = ProvisioningResponseDispatcher.__updateVMafterFAILED(
                        actionModel, vm)
                else:
                    vm.setState(VirtualMachine.UNKNOWN_STATE)

                try:
                    logging.debug("Sending response to Plugin in sendAsync")
                    if str(actionModel.callBackUrl) == 'SFA.OCF.VTM':
                        logging.debug(">>>>>>> SFA.OCF.VTM\n\n\n")
                        if failedOnCreate:
                            logging.debug(
                                "........... failedOnCreate.........")
                            expiring_slices = vm.objects.filter(
                                sliceName=vm.sliceName,
                                projectName=vm.projectName)
                            logging.debug(
                                "........... expiring_slices: %s ..........." %
                                str(expiring_slices))
                            if len(expiring_slices) == 1:
                                expiring_slices[0].delete()

                    # Cleaning up reservation objects
                    ProvisioningResponseDispatcher.__clean_up_reservations(
                        vm.name)

                    XmlRpcClient.callRPCMethod(vm.getCallBackURL(), "sendSync",
                                               XmlHelper.craftXmlClass(rspec))
                    if failedOnCreate == 1:
                        controller.deleteVM(vm)
                        # Keep actions table up-to-date after each deletion
                        actionModel.delete()
                except Exception as e:
                    logging.error(
                        "Could not connect to Plugin in sendSync. Exception: %s",
                        e)
                    return

            # If response is for a finished action
            else:
                try:
                    #XXX: What should be done if this happen?
                    logging.error(
                        "Received response for an action in wrong state")
                    XmlRpcClient.callRPCMethod(
                        vm.getCallBackURL(), "sendSync",
                        XmlHelper.getProcessingResponse(
                            Action.ACTION_STATUS_FAILED_TYPE, action,
                            "Received response for an action in wrong state"))
                except Exception as e:
                    logging.error(e)
                    return
	def processResponse(rspec):
		logging.debug("PROCESSING RESPONSE processResponse() STARTED...")
		for action in rspec.response.provisioning.action:
			try:
				actionModel = ActionController.getAction(action.id)
			except Exception as e:
				logging.error("No action in DB with the incoming uuid\n%s", e)
				return

			'''
			If the response is for an action only in QUEUED or ONGOING status, SUCCESS or FAILED actions are finished
			'''
			#if str(actionModel.callBackUrl) == str(SfaCommunicator.SFAUrl): #Avoiding unicodes
			#	event = pull(str(action.id))
			#	event.send('continue')
			#	return

			if actionModel.getStatus() is Action.QUEUED_STATUS or Action.ONGOING_STATUS:
				logging.debug("The incoming response has id: %s and NEW status: %s" % (actionModel.uuid,actionModel.status))
                                was_creating = False
                                was_created = False
                           	actionModel.status = action.status
				actionModel.description = action.description
				actionModel.save()
				#Complete information required for the Plugin: action type and VM
				ActionController.completeActionRspec(action, actionModel)

				#XXX:Implement this method or some other doing this job
				vm = VTDriver.getVMbyUUID(actionModel.getObjectUUID())
                                if vm.state == "creating...":
                                    was_creating = True
                                elif vm.state == "starting...":
                                    was_created = True
				controller=VTDriver.getDriver(vm.Server.get().getVirtTech())
				failedOnCreate = 0
				# Update VM model with new status from OXAD
				if actionModel.getStatus() == Action.SUCCESS_STATUS:
					ProvisioningResponseDispatcher.__updateVMafterSUCCESS(actionModel, vm)
				elif actionModel.getStatus() == Action.ONGOING_STATUS:
					ProvisioningResponseDispatcher.__updateVMafterONGOING(actionModel, vm)
				elif actionModel.getStatus() == Action.FAILED_STATUS:
					failedOnCreate = ProvisioningResponseDispatcher.__updateVMafterFAILED(actionModel, vm)
				else:
					vm.setState(VirtualMachine.UNKNOWN_STATE)
				try:
                                        created = False
                                        vm_started = False
                                        if vm.state == "created (stopped)":
                                            created = True
                                        elif vm.state == "running":
                                            vm_started = True
                                        logging.debug("Sending response to plug-in in sendAsync")
                                        if str(vm.callBackURL) == 'SFA.OCF.VTM':
                                                logging.debug("callback: %s" % vm.callBackURL)
                                                print "-------------->PRD: Created:", created, "Was_creating:", was_creating, "vm_started:", vm_started 
                                                print "-------------->PRD Action:", action, action.server.__dict__ 
                                                # Start VM just after creating sliver/VM
                                                if created and was_creating:
                                                    from vt_manager.communication.sfa.drivers.VTSfaDriver import VTSfaDriver
                                                    driver = VTSfaDriver(None)
                                                    driver.crud_slice(vm.sliceName,vm.projectName, "start_slice")
                                                    ProvisioningResponseDispatcher.__clean_up_reservations(vm.uuid)
                                                    return 
                                                #if was_created and vm_started:
                                                if vm_started:
                                                    ifaces = vm.getNetworkInterfaces()
                                                    for iface in ifaces:
                                                        if iface.isMgmt:
                                                            ip = iface.ip4s.all()[0].ip
                                                    
                                                    # Contextualize VMs
                                                    ProvisioningResponseDispatcher.__contextualize_vm(vm, ip)
                                                    # Cleaning up reservation objects
					        return
					XmlRpcClient.callRPCMethod(vm.getCallBackURL(), "sendAsync", XmlHelper.craftXmlClass(rspec))
					if failedOnCreate == 1:
						controller.deleteVM(vm)
						# Keep actions table up-to-date after each deletion
						actionModel.delete()
				except Exception as e:
					logging.error("Could not connect to Plugin in sendAsync\n%s",e)
					return
			
			#If response is for a finished action
			else:
				try:
					#XXX: What should be done if this happen?
					logging.error("Received response for an action in wrong state\n")
					XmlRpcClient.callRPCMethod(vm.getCallBackURL(), "sendAsync", XmlHelper.getProcessingResponse(Action.ACTION_STATUS_FAILED_TYPE, action, "Received response for an action in wrong state"))
				except Exception as e:
					logging.error(e)
					return
Beispiel #27
0
    def processProvisioning(provisioning):

        logging.debug("PROVISIONING STARTED...\n")
        for action in provisioning.action:
            actionModel = ActionController.ActionToModel(
                action, "provisioning")
            logging.debug("ACTION type: %s with id: %s" %
                          (actionModel.type, actionModel.uuid))

            try:
                RuleTableManager.Evaluate(action,
                                          RuleTableManager.getDefaultName())
            except Exception as e:
                a = str(e)
                if len(a) > 200:
                    a = a[0:199]

                XmlRpcClient.callRPCMethod(
                    threading.currentThread().callBackURL, "sendAsync",
                    XmlHelper.craftXmlClass(
                        XmlHelper.getProcessingResponse(
                            Action.FAILED_STATUS, action, a)))
                #				XmlRpcClient.callRPCMethod(threading.currentThread().callBackURL,"sendAsync",XmlHelper.craftXmlClass(XmlHelper.getProcessingResponse('FAILED', action, 'You requested more than the 128Mbytes allowed for your project')))
                return None
            try:

                controller = VTDriver.getDriver(
                    action.server.virtualization_type)

                #XXX:Change this when xml schema is updated
                server = VTDriver.getServerByUUID(action.server.uuid)
                #if actionModel.getType() == Action.PROVISIONING_VM_CREATE_TYPE:
                #	server = VTDriver.getServerByUUID(action.virtual_machine.server_id)
                #else:
                #	server = VTDriver.getVMbyUUID(action.virtual_machine.uuid).Server.get()
            except Exception as e:
                logging.error(e)
                raise e

            try:
                #PROVISIONING CREATE
                if actionModel.getType() == Action.PROVISIONING_VM_CREATE_TYPE:
                    try:
                        vm = ProvisioningDispatcher.__createVM(
                            controller, actionModel, action)
                    except:
                        vm = None
                        raise
                #PROVISIONING DELETE, START, STOP, REBOOT

                else:

                    ProvisioningDispatcher.__deleteStartStopRebootVM(
                        controller, actionModel, action)

                XmlRpcClient.callRPCMethod(
                    server.getAgentURL(), "send", UrlUtils.getOwnCallbackURL(),
                    1, server.getAgentPassword(),
                    XmlHelper.craftXmlClass(
                        XmlHelper.getSimpleActionQuery(action)))
            except Exception as e:
                if actionModel.getType(
                ) == Action.PROVISIONING_VM_CREATE_TYPE and vm:
                    controller.deleteVM(vm)
                XmlRpcClient.callRPCMethod(
                    threading.currentThread().callBackURL, "sendAsync",
                    XmlHelper.craftXmlClass(
                        XmlHelper.getProcessingResponse(
                            Action.FAILED_STATUS, action, str(e))))

        logging.debug("PROVISIONING FINISHED...")
    def listResources(remoteHashValue, projectUUID='None', sliceUUID='None'):
        logging.debug("Enter listResources")
        infoRspec = XmlHelper.getSimpleInformation()
        servers = VTDriver.getAllServers()
        baseVM = copy.deepcopy(infoRspec.response.information.resources.
                               server[0].virtual_machine[0])
        if not servers:
            logging.debug("No VTServers available")
            infoRspec.response.information.resources.server.pop()
            resourcesString = XmlHelper.craftXmlClass(infoRspec)
            localHashValue = str(hash(resourcesString))
        else:
            for sIndex, server in enumerate(servers):
                if (sIndex == 0):
                    baseServer = copy.deepcopy(
                        infoRspec.response.information.resources.server[0])
                if (sIndex != 0):
                    newServer = copy.deepcopy(baseServer)
                    infoRspec.response.information.resources.server.append(
                        newServer)

                InformationDispatcher.__ServerModelToClass(
                    server,
                    infoRspec.response.information.resources.server[sIndex])
                if (projectUUID is not 'None'):
                    vms = server.getVMs(projectId=projectUUID)
                else:
                    vms = server.getVMs()
                if not vms:
                    logging.debug("No VMs available")
                    if infoRspec.response.information.resources.server[
                            sIndex].virtual_machine:
                        infoRspec.response.information.resources.server[
                            sIndex].virtual_machine.pop()
                elif (sliceUUID is not 'None'):
                    vms = vms.filter(sliceId=sliceUUID)
                    if not vms:
                        logging.error("No VMs available")
                        infoRspec.response.information.resources.server[
                            sIndex].virtual_machine.pop()
                for vIndex, vm in enumerate(vms):
                    if (vIndex != 0):
                        newVM = copy.deepcopy(baseVM)
                        infoRspec.response.information.resources.server[
                            sIndex].virtual_machine.append(newVM)
                    InformationDispatcher.__VMmodelToClass(
                        vm, infoRspec.response.information.resources.
                        server[sIndex].virtual_machine[vIndex])

            resourcesString = XmlHelper.craftXmlClass(infoRspec)
            localHashValue = str(hash(resourcesString))
        try:
            rHashObject = resourcesHash.objects.get(projectUUID=projectUUID,
                                                    sliceUUID=sliceUUID)
            rHashObject.hashValue = localHashValue
            rHashObject.save()
        except:
            rHashObject = resourcesHash(hashValue=localHashValue,
                                        projectUUID=projectUUID,
                                        sliceUUID=sliceUUID)
            rHashObject.save()

        if remoteHashValue == rHashObject.hashValue:
            return localHashValue, ''
        else:
            return localHashValue, resourcesString