コード例 #1
0
def startStopSlice(action, uuid):

    "Manages the actions executed over VMs at url manage resources."
    try:
        vmsToStart = VM.objects.filter(sliceId=uuid)

        #if action_type == 'stop' : action_type = 'hardStop'
        globalRspec = XmlHelper.getSimpleActionSpecificQuery(action, "dummy")
        globalRspec.query.provisioning.action.pop()
        for vm in vmsToStart:
            rspec = XmlHelper.getSimpleActionSpecificQuery(action, vm.serverID)
            Translator.PopulateNewAction(rspec.query.provisioning.action[0],
                                         vm)
            globalRspec.query.provisioning.action.append(
                copy.deepcopy(rspec.query.provisioning.action[0]))

        ServiceThread.startMethodInNewThread(
            ProvisioningDispatcher.processProvisioning,
            globalRspec.query.provisioning, None)

        for vm in vmsToStart:
            if action == 'start':
                vm.state = 'starting...'
            elif action == 'stop':
                vm.state = 'stopping'
            vm.save()
    except Exception as e:
        print e
        raise e
コード例 #2
0
def startStopSlice(action,uuid):

    "Manages the actions executed over VMs at url manage resources."
    try: 
        vmsToStart = VM.objects.filter(sliceId = uuid)
    
        #if action_type == 'stop' : action_type = 'hardStop'
        globalRspec = XmlHelper.getSimpleActionSpecificQuery(action, "dummy")
    	globalRspec.query.provisioning.action.pop()
        for vm in vmsToStart:
            rspec = XmlHelper.getSimpleActionSpecificQuery(action, vm.serverID)
            Translator.PopulateNewAction(rspec.query.provisioning.action[0], vm)
            globalRspec.query.provisioning.action.append(copy.deepcopy(rspec.query.provisioning.action[0]))
    
        ServiceThread.startMethodInNewThread(ProvisioningDispatcher.processProvisioning,globalRspec.query.provisioning, None)
    
        for vm in vmsToStart:
            if action == 'start':
            	vm.state = 'starting...'
            elif action == 'stop':
                vm.state = 'stopping'
            vm.save()
    except Exception as e:
        print e
        raise e
コード例 #3
0
 def connectAndSend(URL, action):
     try:
         vt_manager = xmlrpclib.Server(URL)
         vt_manager.send(PLUGIN_URL, XmlHelper.craftXmlClass(XmlHelper.getSimpleActionQuery(action)))
     except Exception as e:
         print "Exception connecting to VT Manager"
         print e
         return
コード例 #4
0
	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
コード例 #5
0
 def connectAndSend(URL, action, client):
     try:
         vt_manager = xmlrpclib.Server(URL)
         PLUGIN_URL = (
             "https://" + client.username + ":" + client.password + "@" + SITE_IP_ADDR + "/vt_plugin/xmlrpc/vt_am/"
         )
         vt_manager.send(PLUGIN_URL, XmlHelper.craftXmlClass(XmlHelper.getSimpleActionQuery(action)))
     except Exception as e:
         logging.error("Exception connecting to VT Manager")
         logging.error(e)
         return
コード例 #6
0
 def connectAndSend(URL, action, client):
     try:
         vt_manager = xmlrpclib.Server(URL)
         PLUGIN_URL = 'https://' + client.username + ':' + client.password + '@' + SITE_IP_ADDR + '/vt_plugin/xmlrpc/vt_am/'
         vt_manager.send(
             PLUGIN_URL,
             XmlHelper.craftXmlClass(
                 XmlHelper.getSimpleActionQuery(action)))
     except Exception as e:
         logging.error("Exception connecting to VT Manager")
         logging.error(e)
         return
コード例 #7
0
	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
コード例 #8
0
	def PropagateActionToProvisioningDispatcher(vm_id, serverUUID, action):
		from vt_manager.communication.utils.XmlHelper import XmlHelper
		from vt_manager.controller.dispatchers.xmlrpc.DispatcherLauncher import DispatcherLauncher
		vm = VirtualMachine.objects.get(id=vm_id).getChildObject()
		rspec = XmlHelper.getSimpleActionSpecificQuery(action, serverUUID)
		ActionController.PopulateNewActionWithVM(rspec.query.provisioning.action[0], vm)
		ServiceThread.startMethodInNewThread(DispatcherLauncher.processXmlQuery, rspec)
コード例 #9
0
    def getActionInstance(servers_slivers, projectName, sliceName):
        provisioningRSpecs = list()
        rspec = XmlHelper.getSimpleActionQuery()
        actionClassEmpty = copy.deepcopy(rspec.query.provisioning.action[0])
        actionClassEmpty.type_ = "create"
        rspec.query.provisioning.action.pop()
        for vms in servers_slivers:
            server_id = vms['component_id']
            for vm in vms['slivers']:
                server = VTServer.objects.get(uuid=server_id)
                VMSfaManager.setDefaultVMParameters(vm, server, projectName,
                                                    sliceName)
                actionClass = copy.deepcopy(actionClassEmpty)
                actionClass.id = uuid.uuid4()
                Translator.VMdictToClass(
                    vm, actionClass.server.virtual_machines[0])
                Translator.VMdicIfacesToClass(
                    vm['interfaces'], actionClass.server.virtual_machines[0].
                    xen_configuration.interfaces)
                actionClass.server.uuid = server_id
                actionClass.server.virtualization_type = server.getVirtTech()
                rspec.query.provisioning.action.append(actionClass)
                provisioningRSpecs.append(rspec.query.provisioning)

        return provisioningRSpecs
コード例 #10
0
def manage_vm(request, slice_id, vm_id, action_type):
    "Manages the actions executed over VMs at url manage resources."
    if not (action_type.startswith("force")):
        vm = VM.objects.get(id = vm_id)
        rspec = XmlHelper.getSimpleActionSpecificQuery(action_type, vm.serverID)
        Translator.PopulateNewAction(rspec.query.provisioning.action[0], vm)
        ServiceThread.startMethodInNewThread(ProvisioningDispatcher.processProvisioning,rspec.query.provisioning, request.user)
        if action_type == 'start':
            vm.state = 'starting...'
        elif action_type == 'stop':
            vm.state = 'stopping...'
        elif action_type == 'reboot':
            vm.state = 'rebooting...'
        elif action_type == 'delete':
            vm.state = 'deleting...'
            # Delete the associated entry in the database
            Action.objects.all().filter(vm = vm).delete()
            # Keep actions table up-to-date after each deletion
            #Action.objects.all().exclude(vm__in = VM.objects.all()).delete()
        elif action_type == 'create':
            vm.state = 'creating...'
        vm.save()

    elif action_type == "force_update_vm":
        InformationDispatcher.force_update_vms(vm_id=vm_id)
    elif action_type == "force_update_server":
        InformationDispatcher.force_update_vms(client_id=vm_id)
    elif action_type == "force_update_all":
        for server in VTServer.objects.all():
             InformationDispatcher.force_update_vms(client_id=server.id) 
    #go to manage resources again
    response = HttpResponse("")
    return response
コード例 #11
0
ファイル: GUIdispatcher.py プロジェクト: cargious/ocf
def manage_vm(request, slice_id, vm_id, action_type):

    "Manages the actions executed over VMs at url manage resources."

    vm = VM.objects.get(id = vm_id)
    #if action_type == 'stop' : action_type = 'hardStop'
    rspec = XmlHelper.getSimpleActionSpecificQuery(action_type, vm.serverID)
    Translator.PopulateNewAction(rspec.query.provisioning.action[0], vm)

    ServiceThread.startMethodInNewThread(ProvisioningDispatcher.processProvisioning,rspec.query.provisioning, request.user)

    #set temporally status
    #vm.state = "on queue"
    if action_type == 'start':
        vm.state = 'starting...'
    elif action_type == 'stop':
        vm.state = 'stopping...'
    elif action_type == 'reboot':
        vm.state = 'rebooting...'
    elif action_type == 'delete':
        vm.state = 'deleting...'
    elif action_type == 'create':
        vm.state = 'creating...'
    vm.save()
    #go to manage resources again
    #return HttpResponseRedirect(reverse("html_plugin_home",args=[slice_id]))
    response = HttpResponse("")
    return response
コード例 #12
0
ファイル: VMMonitor.py プロジェクト: cargious/ocf
    def sendUpdateVMs(server):
        #Recover from the client the list of active VMs
        obj = XmlHelper.getListActiveVMsQuery()

        #Create new Action
        action = ActionController.createNewAction(
            Action.MONITORING_SERVER_VMS_TYPE, Action.QUEUED_STATUS,
            server.getUUID(), "")

        obj.query.monitoring.action[0].id = action.getUUID()
        obj.query.monitoring.action[
            0].server.virtualization_type = server.getid = server.getVirtTech(
            )
        XmlRpcClient.callRPCMethod(server.getAgentURL(), "send",
                                   UrlUtils.getOwnCallbackURL(), 0,
                                   server.agentPassword,
                                   XmlHelper.craftXmlClass(obj))
コード例 #13
0
ファイル: VMMonitor.py プロジェクト: HalasNet/felix
	def sendUpdateVMs(server):
		#Recover from the client the list of active VMs
		obj = XmlHelper.getListActiveVMsQuery()
	
		#Create new Action 
		action = ActionController.createNewAction(Action.MONITORING_SERVER_VMS_TYPE,Action.QUEUED_STATUS,server.getUUID(),"") 

			
		obj.query.monitoring.action[0].id = action.getUUID() 
		obj.query.monitoring.action[0].server.virtualization_type = server.getid = server.getVirtTech() 
		XmlRpcClient.callRPCMethod(server.getAgentURL(),"send",UrlUtils.getOwnCallbackURL(),0,server.agentPassword,XmlHelper.craftXmlClass(obj))
コード例 #14
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:
				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...")
コード例 #15
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:
				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...")
コード例 #16
0
ファイル: vtam.py プロジェクト: HalasNet/felix
    def get_action_instance(self, reservation):
 	rspec = XmlHelper.getSimpleActionQuery()
 	actionClass = copy.deepcopy(rspec.query.provisioning.action[0])
        actionClass.type_ = "create"
        rspec.query.provisioning.action.pop()
        #server = reservation.server()
        server = reservation.server
 	vm = self.get_default_vm_parameters(reservation)
        actionClass.id = uuid.uuid4()
        self.vm_dict_to_class(vm, actionClass.server.virtual_machines[0])
 	self.vm_dict_ifaces_to_class(vm["interfaces"],actionClass.server.virtual_machines[0].xen_configuration.interfaces)
        actionClass.server.uuid = server.uuid
        actionClass.server.virtualization_type = server.getVirtTech()
        rspec.query.provisioning.action.append(actionClass)
        return rspec.query.provisioning
コード例 #17
0
 def get_action_instance(self, reservation):
     rspec = XmlHelper.getSimpleActionQuery()
     actionClass = copy.deepcopy(rspec.query.provisioning.action[0])
     actionClass.type_ = "create"
     rspec.query.provisioning.action.pop()
     #server = reservation.server()
     server = reservation.server
     vm = self.get_default_vm_parameters(reservation)
     actionClass.id = uuid.uuid4()
     self.vm_dict_to_class(vm, actionClass.server.virtual_machines[0])
     self.vm_dict_ifaces_to_class(
         vm["interfaces"], actionClass.server.virtual_machines[0].
         xen_configuration.interfaces)
     actionClass.server.uuid = server.uuid
     actionClass.server.virtualization_type = server.getVirtTech()
     rspec.query.provisioning.action.append(actionClass)
     return rspec.query.provisioning
コード例 #18
0
ファイル: VMMonitor.py プロジェクト: HalasNet/felix
	def processUpdateVMsListFromCallback(vmUUID,state,rspec):
		from vt_manager.models.VirtualMachine import VirtualMachine
		try:
			VM = VirtualMachine.objects.get(uuid = vmUUID)

		except Exception as e:
			raise e

		if state == 'Started':
			VM.setState(VirtualMachine.RUNNING_STATE)
		elif state == 'Stopped':
			VM.setState(VirtualMachine.STOPPED_STATE)
		else:
			VM.setState(VirtualMachine.UNKNOWN_STATE)
		
		#XXX: Maybe there better palces to send to expedient this update state...	
		XmlRpcClient.callRPCMethod(VM.getCallBackURL(), "sendAsync", XmlHelper.craftXmlClass(rspec))				
コード例 #19
0
    def processUpdateVMsListFromCallback(vmUUID, state, rspec):
        from vt_manager.models.VirtualMachine import VirtualMachine
        try:
            VM = VirtualMachine.objects.get(uuid=vmUUID)

        except Exception as e:
            raise e

        if state == 'Started':
            VM.setState(VirtualMachine.RUNNING_STATE)
        elif state == 'Stopped':
            VM.setState(VirtualMachine.STOPPED_STATE)
        else:
            VM.setState(VirtualMachine.UNKNOWN_STATE)

        #XXX: Maybe there better palces to send to expedient this update state...
        XmlRpcClient.callRPCMethod(VM.getCallBackURL(), "sendAsync",
                                   XmlHelper.craftXmlClass(rspec))
コード例 #20
0
    def processVMCreation(instances, server_id, slice, requestUser):

        rspec = XmlHelper.getSimpleActionQuery()
        actionClassEmpty = copy.deepcopy(rspec.query.provisioning.action[0])
        actionClassEmpty.type_ = "create"
        rspec.query.provisioning.action.pop()
        for instance in instances:
            instance.uuid = uuid.uuid4()
            instance.serverID = server_id
            instance.state = "on queue"
            instance.sliceId = slice.uuid
            instance.sliceName = slice.name

            #assign same virt technology as the server where vm created
            s = VTServer.objects.get(uuid=server_id)
            instance.virtTech = s.virtTech
            instance.projectId = slice.project.uuid
            instance.projectName = slice.project.name
            instance.aggregate_id = s.aggregate_id
            #assign parameters according to selected disc image
            #TODO get the rest of image choices!
            if instance.disc_image == 'test':
                instance.operatingSystemType = 'GNU/Linux'
                instance.operatingSystemVersion = '6.0'
                instance.operatingSystemDistribution = 'Debian'
                instance.hdOriginPath = "default/test/lenny"
            if instance.disc_image == 'default':
                instance.operatingSystemType = 'GNU/Linux'
                instance.operatingSystemVersion = '6.0'
                instance.operatingSystemDistribution = 'Debian'
                instance.hdOriginPath = "default/default.tar.gz"

            actionClass = copy.deepcopy(actionClassEmpty)
            actionClass.id = uuid.uuid4()
            Translator.VMmodelToClass(instance,
                                      actionClass.server.virtual_machines[0])
            server = VTServer.objects.get(uuid=server_id)
            actionClass.server.uuid = server_id
            actionClass.server.virtualization_type = server.getVirtTech()
            rspec.query.provisioning.action.append(actionClass)

        ServiceThread.startMethodInNewThread(
            ProvisioningDispatcher.processProvisioning,
            rspec.query.provisioning, requestUser)
コード例 #21
0
ファイル: VMSfaManager.py プロジェクト: fp7-alien/C-BAS
    def getActionInstance(servers_slivers,projectName,sliceName):
	provisioningRSpecs = list()
	rspec = XmlHelper.getSimpleActionQuery()
	actionClassEmpty = copy.deepcopy(rspec.query.provisioning.action[0])
        actionClassEmpty.type_ = "create"
        rspec.query.provisioning.action.pop()
        for vms in servers_slivers:
	    server_id = vms['component_id']
	    for vm in vms['slivers']:
		server = VTServer.objects.get(uuid = server_id)
	        VMSfaManager.setDefaultVMParameters(vm,server,projectName,sliceName)
		actionClass = copy.deepcopy(actionClassEmpty)
                actionClass.id = uuid.uuid4()
                Translator.VMdictToClass(vm, actionClass.server.virtual_machines[0])
		Translator.VMdicIfacesToClass(vm['interfaces'],actionClass.server.virtual_machines[0].xen_configuration.interfaces)
                actionClass.server.uuid = server_id
                actionClass.server.virtualization_type = server.getVirtTech()
                rspec.query.provisioning.action.append(actionClass)
		provisioningRSpecs.append(rspec.query.provisioning)

	return provisioningRSpecs
コード例 #22
0
def manage_vm(request, slice_id, vm_id, action_type):
    "Manages the actions executed over VMs at url manage resources."
    if not (action_type.startswith("force")):
        vm = VM.objects.get(id=vm_id)
        rspec = XmlHelper.getSimpleActionSpecificQuery(action_type,
                                                       vm.serverID)
        Translator.PopulateNewAction(rspec.query.provisioning.action[0], vm)
        ServiceThread.startMethodInNewThread(
            ProvisioningDispatcher.processProvisioning,
            rspec.query.provisioning, request.user)
        if action_type == 'start':
            vm.state = 'starting...'
        elif action_type == 'stop':
            vm.state = 'stopping...'
        elif action_type == 'reboot':
            vm.state = 'rebooting...'
        elif action_type == 'delete':
            vm.state = 'deleting...'
            # Delete the associated entry in the database
            Action.objects.all().filter(vm=vm).delete()
            # Keep actions table up-to-date after each deletion
            #Action.objects.all().exclude(vm__in = VM.objects.all()).delete()
        elif action_type == 'create':
            vm.state = 'creating...'
        vm.save()

    elif action_type == "force_update_vm":
        InformationDispatcher.force_update_vms(vm_id=vm_id)
    elif action_type == "force_update_server":
        InformationDispatcher.force_update_vms(client_id=vm_id)
    elif action_type == "force_update_all":
        for server in VTServer.objects.all():
            InformationDispatcher.force_update_vms(client_id=server.id)
    #go to manage resources again
    response = HttpResponse("")
    return response
コード例 #23
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
コード例 #24
0
    def processVMCreation(instance, server_id, slice, requestUser):

        if VM.objects.filter(sliceId=slice.uuid, name=instance.name):
            raise ValidationError(
                "Another VM with name %s already exists in this slice. Please choose a new name"
                % instance.name)
        rspec = XmlHelper.getSimpleActionQuery()
        actionClassEmpty = copy.deepcopy(rspec.query.provisioning.action[0])
        actionClassEmpty.type_ = "create"
        rspec.query.provisioning.action.pop()

        instance.uuid = uuid.uuid4()
        instance.serverID = server_id
        instance.state = "on queue"
        instance.sliceId = slice.uuid
        instance.sliceName = slice.name

        #assign same virt technology as the server where vm created
        s = VTServer.objects.get(uuid=server_id)
        instance.virtTech = s.virtTech
        instance.projectId = slice.project.uuid
        instance.projectName = slice.project.name
        instance.aggregate_id = s.aggregate_id
        #assign parameters according to selected disc image
        #TODO get the rest of image choices!
        if instance.disc_image == 'test':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '6.0'
            instance.operatingSystemDistribution = 'Debian'
            instance.hdOriginPath = "default/test/lenny"
        if instance.disc_image == 'default':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '6.0'
            instance.operatingSystemDistribution = 'Debian'
            instance.hdOriginPath = "default/default.tar.gz"
            instance.virtualization_setup_type = "paravirtualization"
        if instance.disc_image == 'legacy':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '6.0'
            instance.operatingSystemDistribution = 'Debian'
            instance.hdOriginPath = "legacy/legacy.tar.gz"
            instance.virtualization_setup_type = "paravirtualization"
        if instance.disc_image == 'irati':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '7.0'
            instance.operatingSystemDistribution = 'Debian'
            instance.hdOriginPath = "irati/irati.img"
            instance.virtualization_setup_type = "hvm"
        if instance.disc_image == 'spirent':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '6.2'
            instance.operatingSystemDistribution = 'CentOS'
            instance.hdOriginPath = "spirentSTCVM/spirentSTCVM.img"
            instance.virtualization_setup_type = "hvm"
        if instance.disc_image == 'debian7':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '7.0'
            instance.operatingSystemDistribution = 'Debian'
            instance.hdOriginPath = "debian7/debian7.img"
            instance.virtualization_setup_type = "hvm"
        actionClass = copy.deepcopy(actionClassEmpty)
        actionClass.id = uuid.uuid4()
        Translator.VMmodelToClass(instance,
                                  actionClass.server.virtual_machines[0])
        server = VTServer.objects.get(uuid=server_id)
        actionClass.server.uuid = server_id
        actionClass.server.virtualization_type = server.getVirtTech()
        rspec.query.provisioning.action.append(actionClass)

        ServiceThread.startMethodInNewThread(
            ProvisioningDispatcher.processProvisioning,
            rspec.query.provisioning, requestUser)
コード例 #25
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...")
コード例 #26
0
    def prepare_vm_class(self):
        rspec = XmlHelper.getSimpleActionQuery()
	actionClassEmpty = copy.deepcopy(rspec.query.provisioning.action[0])
        actionClassEmpty.type_ = "create"
        rspec.query.provisioning.action.pop()
        return actionClassEmpty.server.virtual_machines[0]
コード例 #27
0
def askForAggregateResources(vtPlugin, projectUUID = 'None', sliceUUID = 'None'):
    "asks the VT AM for all the resources under it."
    serversInAggregate = []
    try:
        client = xmlrpclib.Server('https://'+vtPlugin.client.username+':'+vtPlugin.client.password+'@'+vtPlugin.client.url[8:])
    except Exception as e:
        print "Can't connect to server: %s" % str(e)
        return
    
    try:
        rHashObject =  resourcesHash.objects.get(vtamID = vtPlugin.id, projectUUID = projectUUID, sliceUUID = sliceUUID)
    except:
        rHashObject = resourcesHash(hashValue = '0', vtamID = vtPlugin.id, projectUUID= projectUUID, sliceUUID = sliceUUID)
        rHashObject.save()
    try:
        remoteHashValue ,resourcesString = client.listResources(rHashObject.hashValue, projectUUID, sliceUUID)
        print remoteHashValue
    except Exception as e:
        print "Can't retrieve resources: %s" % str(e)
        return

    if remoteHashValue == rHashObject.hashValue:
        print "Same HASH, no changes in resources"
        return
    else:
        print remoteHashValue
        oldHashValue = rHashObject.hashValue
        rHashObject.hashValue = remoteHashValue
        rHashObject.save() 
        try:
            xmlClass = XmlHelper.parseXmlString(resourcesString)
        except Exception as e:
            print "Can't parse rspec: %s" % str(e)
            return
        try:
            for server in xmlClass.response.information.resources.server:
                vmsInAggregate = []
                for vm in server.virtual_machine:
                    #Translate and register VM present in the AM
                    VMmodel = Translator.VMtoModel(vm, vtPlugin.id, save="save")
                    Translator.PopulateNewVMifaces(vm, VMmodel)
                    vmsInAggregate.append(VMmodel.uuid)
                #Translate The whole server with the vms updated. There may be still VMs in the models
                #which are not in the AM
                serverModel = Translator.ServerClassToModel(server, vtPlugin.id)
                # Delete VMs in the model that are not in the linked to the server in the AM
                for vmuuid in serverModel.vms.filter(sliceId=sliceUUID, projectId=projectUUID).values_list('uuid', flat=True):                

                    try:
                        action_present = False
                        action_create =  Action.objects.get(vm__uuid=vmuuid)
                        if action_create.type=="create" and action_create.status=="SUCCESS":
                            action_present = True
                    except:
                        print "VM Manager returned a VM which has not provisioning create action associated"
                    if vmuuid not in vmsInAggregate and action_present:
                        vmToDelete = VM.objects.get(uuid=vmuuid)
                        serverModel.vms.remove(vmToDelete)
                        vmToDelete.completeDelete() 
                serversInAggregate.append(server.uuid)
                #Update VMs in the server model
                serverModel.setVMs()
            serversInExpedient  = VTServer.objects.filter(aggregate=vtPlugin.id).values_list('uuid', flat=True)
            #Delete servers in Expedient that are not any more in the AM. VMs in that server included
            for s in serversInExpedient:
                if s not in serversInAggregate:
                    delServer = VTServer.objects.get(uuid = s)
                    delServer.completeDelete()
                
            return xmlClass


        except Exception as e:
            print e
            rHashObject.hashValue = oldHashValue
            rHashObject.save()
コード例 #28
0
ファイル: VMcontroller.py プロジェクト: fp7-alien/C-BAS
    def processVMCreation(instance, server_id, slice, requestUser):

        if VM.objects.filter(sliceId = slice.uuid, name =instance.name):
            raise ValidationError("Another VM with name %s already exists in this slice. Please choose a new name" % instance.name)
        rspec = XmlHelper.getSimpleActionQuery()
        actionClassEmpty = copy.deepcopy(rspec.query.provisioning.action[0])
        actionClassEmpty.type_ = "create"
        rspec.query.provisioning.action.pop()

        instance.uuid = uuid.uuid4()
        instance.serverID = server_id
        instance.state = "on queue"
        instance.sliceId = slice.uuid
        instance.sliceName= slice.name

        #assign same virt technology as the server where vm created
        s = VTServer.objects.get(uuid = server_id)
        instance.virtTech = s.virtTech
        instance.projectId = slice.project.uuid
        instance.projectName = slice.project.name
        instance.aggregate_id = s.aggregate_id
        #assign parameters according to selected disc image
        #TODO get the rest of image choices! 
        if instance.disc_image == 'test':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '6.0'
            instance.operatingSystemDistribution = 'Debian'
            instance.hdOriginPath = "default/test/lenny"
        if instance.disc_image == 'default':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '6.0'
            instance.operatingSystemDistribution = 'Debian'
            instance.hdOriginPath = "default/default.tar.gz"
            instance.virtualization_setup_type = "paravirtualization"
        if instance.disc_image == 'legacy':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '6.0'
            instance.operatingSystemDistribution = 'Debian'
            instance.hdOriginPath = "legacy/legacy.tar.gz"
            instance.virtualization_setup_type = "paravirtualization"
        if instance.disc_image == 'irati':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '7.0'
            instance.operatingSystemDistribution = 'Debian'
            instance.hdOriginPath = "irati/irati.img"
            instance.virtualization_setup_type = "hvm"
        if instance.disc_image == 'spirent':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '6.2'
            instance.operatingSystemDistribution = 'CentOS'
            instance.hdOriginPath = "spirent/spirentSTCVM.img"
            instance.virtualization_setup_type = "hvm"
        if instance.disc_image == 'debian7':
            instance.operatingSystemType = 'GNU/Linux'
            instance.operatingSystemVersion = '7.0'
            instance.operatingSystemDistribution = 'Debian'
            instance.hdOriginPath = "debian7/debian7.img"
            instance.virtualization_setup_type = "hvm"
        actionClass = copy.deepcopy(actionClassEmpty)
        actionClass.id = uuid.uuid4()
        Translator.VMmodelToClass(instance, actionClass.server.virtual_machines[0])
        server = VTServer.objects.get(uuid = server_id)
        actionClass.server.uuid = server_id
        actionClass.server.virtualization_type = server.getVirtTech()
        rspec.query.provisioning.action.append(actionClass)
         
        ServiceThread.startMethodInNewThread(ProvisioningDispatcher.processProvisioning,rspec.query.provisioning, requestUser)
コード例 #29
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
コード例 #30
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
コード例 #31
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
コード例 #32
0
ファイル: vtAggregateController.py プロジェクト: cargious/ocf
def askForAggregateResources(vtPlugin, projectUUID='None', sliceUUID='None'):
    "asks the VT AM for all the resources under it."
    serversInAggregate = []
    try:
        client = xmlrpclib.Server('https://' + vtPlugin.client.username + ':' +
                                  vtPlugin.client.password + '@' +
                                  vtPlugin.client.url[8:])
    except Exception as e:
        print "Can't connect to server"
        print e
        return

    try:
        rHashObject = resourcesHash.objects.get(vtamID=vtPlugin.id,
                                                projectUUID=projectUUID,
                                                sliceUUID=sliceUUID)
    except:
        rHashObject = resourcesHash(hashValue='0',
                                    vtamID=vtPlugin.id,
                                    projectUUID=projectUUID,
                                    sliceUUID=sliceUUID)
        rHashObject.save()
    try:
        remoteHashValue, resourcesString = client.listResources(
            rHashObject.hashValue, projectUUID, sliceUUID)
        print remoteHashValue
    except Exception as e:
        print "Can't retrieve resources"
        print e
        return

    if remoteHashValue == rHashObject.hashValue:
        print "Same HASH, no changes in resources"
        return
    else:
        print remoteHashValue
        oldHashValue = rHashObject.hashValue
        rHashObject.hashValue = remoteHashValue
        rHashObject.save()
        try:
            xmlClass = XmlHelper.parseXmlString(resourcesString)
        except Exception as e:
            print "Can't parse rspec"
            print e
            return
        try:
            for server in xmlClass.response.information.resources.server:
                vmsInAggregate = []
                for vm in server.virtual_machine:
                    #Translate and register VM present in the AM
                    VMmodel = Translator.VMtoModel(vm,
                                                   vtPlugin.id,
                                                   save="save")
                    Translator.PopulateNewVMifaces(vm, VMmodel)
                    vmsInAggregate.append(VMmodel.uuid)
                #Translate The whole server with the vms updated. There may be still VMs in the models
                #which are not in the AM
                serverModel = Translator.ServerClassToModel(
                    server, vtPlugin.id)
                # Delete VMs in the model that are not in the linked to the server in the AM
                for vmuuid in serverModel.vms.filter(
                        sliceId=sliceUUID,
                        projectId=projectUUID).values_list('uuid', flat=True):
                    if vmuuid not in vmsInAggregate:
                        vmToDelete = VM.objects.get(uuid=vmuuid)
                        serverModel.vms.remove(vmToDelete)
                        vmToDelete.completeDelete()
                serversInAggregate.append(server.uuid)
                #Update VMs in the server model
                serverModel.setVMs()
            serversInExpedient = VTServer.objects.filter(
                aggregate=vtPlugin.id).values_list('uuid', flat=True)
            #Delete servers in Expedient that are not any more in the AM. VMs in that server included
            for s in serversInExpedient:
                if s not in serversInAggregate:
                    delServer = VTServer.objects.get(uuid=s)
                    delServer.completeDelete()

            return xmlClass

        except Exception as e:
            print e
            rHashObject.hashValue = oldHashValue
            rHashObject.save()
コード例 #33
0
    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