def run(self):
     while not self.finish() :
         commandIDs = self.__dbConnector.removeOldCommands(self.__commandTimeout)
         (outputType, commandOutput) = CommandsHandler.createCommandTimeoutErrorOutput()
         for commandID in commandIDs :
             self.__dbConnector.addCommandOutput(commandID, outputType, commandOutput, True)
         sleep(self.__sleepTime)
 def changeVMServerConfiguration(self, serverNameOrIPAddress, newName,
                                 newIPAddress, newPort,
                                 newVanillaImageEditionBehavior):
     (commandType, commandArgs
      ) = CommandsHandler.createVMServerConfigurationChangeCommand(
          serverNameOrIPAddress, newName, newIPAddress, newPort,
          newVanillaImageEditionBehavior)
     return self.__commandsDBConnector.addCommand(self.__userID,
                                                  commandType, commandArgs)
 def destroyDomain(self, domainID):
     """
     Destruye una máquina virtual
     Argumentos:
         domainID: el identificador único de la máquina virtual a destruir
     Devuelve:
         Nada
     """
     (commandType, commandArgs) = CommandsHandler.createDomainDestructionCommand(domainID)
     return self.__commandsDBConnector.addCommand(self.__userID, commandType, commandArgs)
 def processCommands(self):
     """
     Procesa los comandos enviados desde los conectores
     Argumentos:
         Ninguno
     Devuelve:
         Nada
     """
     while not self.__stopped :
         commandData = self.__commandsDBConnector.popCommand()
         if (commandData == None) :
             sleep(0.1)
         else :
             (commandID, commandType, commandArgs) = commandData
             parsedArgs = CommandsHandler.deserializeCommandArgs(commandType, commandArgs)
             if (commandType != COMMAND_TYPE.HALT) :
                 serializedCommandID = "{0}|{1}".format(commandID[0], commandID[1])                    
                 if (commandType == COMMAND_TYPE.BOOTUP_VM_SERVER) :                    
                     packet = self.__repositoryPacketHandler.createVMServerBootUpPacket(parsedArgs["VMServerNameOrIP"], serializedCommandID)
                 elif (commandType == COMMAND_TYPE.REGISTER_VM_SERVER) :
                     packet = self.__repositoryPacketHandler.createVMServerRegistrationPacket(parsedArgs["VMServerIP"], 
                         parsedArgs["VMServerPort"], parsedArgs["VMServerName"], parsedArgs["IsVanillaServer"], serializedCommandID)
                 elif (commandType == COMMAND_TYPE.UNREGISTER_OR_SHUTDOWN_VM_SERVER) :
                     packet = self.__repositoryPacketHandler.createVMServerUnregistrationOrShutdownPacket(parsedArgs["VMServerNameOrIP"], 
                         parsedArgs["Halt"], parsedArgs["Unregister"], serializedCommandID)
                 elif (commandType == COMMAND_TYPE.VM_BOOT_REQUEST) :
                     packet = self.__repositoryPacketHandler.createVMBootRequestPacket(parsedArgs["VMID"], parsedArgs["UserID"], serializedCommandID)
                 elif (commandType == COMMAND_TYPE.DESTROY_DOMAIN):
                     packet = self.__repositoryPacketHandler.createDomainDestructionPacket(parsedArgs["DomainID"], serializedCommandID)
                 elif (commandType == COMMAND_TYPE.VM_SERVER_CONFIGURATION_CHANGE) :
                     packet = self.__repositoryPacketHandler.createVMServerConfigurationChangePacket(parsedArgs["VMServerNameOrIPAddress"],  parsedArgs["NewServerName"],
                                                                                      parsedArgs["NewServerIPAddress"], parsedArgs["NewServerPort"],
                                                                                      parsedArgs["NewVanillaImageEditionBehavior"], serializedCommandID)
                 errorMessage = self.__manager.sendPacket(self.__clusterServerIP, self.__clusterServerPort, packet)
                 if (errorMessage != None) :
                     # Error al enviar el paquete => el comando no se podrá ejecutar => avisar a la web
                     (outputType, outputContent) = CommandsHandler.createConnectionErrorOutput()
                     self.__commandsDBConnector.addCommandOutput(commandID, outputType, outputContent)
                     
             else :
                 self.__stopped = True
                 self.__haltVMServers = parsedArgs["HaltVMServers"]
 def bootUpVMServer(self, vmServerNameOrIP):
     """
     Arranca un servidor de máquinas virtuales y lo añade a la infraestructura
     Argumentos:
         vmServerNameOrIP: el nombre o la IP del servidor a arrancar
     Devuelve:
         El identificador único del comando.
         @attention: La representación del identificador único del comando puede cambiar sin previo aviso.
     """
     (commandType, commandArgs) = CommandsHandler.createVMServerBootCommand(vmServerNameOrIP)
     return self.__commandsDBConnector.addCommand(self.__userID, commandType, commandArgs)
 def isShutDown(self, haltVMServers):
     """
     Apaga toda la infraestructura
     Argumentos:
         haltVMServers: si es True, el servidor se apagará inmediatamente. Si es False, esperará a que los usuarios apaguen sus
         máquinas virtuales.
     Devuelve: 
         Nada
     """
     (commandType, commandArgs) = CommandsHandler.createHaltCommand(haltVMServers)
     self.__commandsDBConnector.addCommand(self.__userID, commandType, commandArgs)
 def bootUpVM(self, imageID):
     """
     Solicita a la infraestructura el arranque de una máquina virtual
     Argumentos:
         imageID: el identificador único de la imagen a arrancar
     Devuelve:
         El identificador único del comando.
         @attention: La representación del identificador único del comando puede cambiar sin previo aviso.
     """
     (commandType, commandArgs) = CommandsHandler.createVMBootCommand(imageID, self.__userID)
     return self.__commandsDBConnector.addCommand(self.__userID, commandType, commandArgs)
 def destroyDomain(self, domainID):
     """
     Destruye una máquina virtual
     Argumentos:
         domainID: el identificador único de la máquina virtual a destruir
     Devuelve:
         Nada
     """
     (commandType, commandArgs
      ) = CommandsHandler.createDomainDestructionCommand(domainID)
     return self.__commandsDBConnector.addCommand(self.__userID,
                                                  commandType, commandArgs)
 def isShutDown(self, haltVMServers):
     """
     Apaga toda la infraestructura
     Argumentos:
         haltVMServers: si es True, el servidor se apagará inmediatamente. Si es False, esperará a que los usuarios apaguen sus
         máquinas virtuales.
     Devuelve: 
         Nada
     """
     (commandType,
      commandArgs) = CommandsHandler.createHaltCommand(haltVMServers)
     self.__commandsDBConnector.addCommand(self.__userID, commandType,
                                           commandArgs)
 def bootUpVM(self, imageID):
     """
     Solicita a la infraestructura el arranque de una máquina virtual
     Argumentos:
         imageID: el identificador único de la imagen a arrancar
     Devuelve:
         El identificador único del comando.
         @attention: La representación del identificador único del comando puede cambiar sin previo aviso.
     """
     (commandType, commandArgs) = CommandsHandler.createVMBootCommand(
         imageID, self.__userID)
     return self.__commandsDBConnector.addCommand(self.__userID,
                                                  commandType, commandArgs)
 def bootUpVMServer(self, vmServerNameOrIP):
     """
     Arranca un servidor de máquinas virtuales y lo añade a la infraestructura
     Argumentos:
         vmServerNameOrIP: el nombre o la IP del servidor a arrancar
     Devuelve:
         El identificador único del comando.
         @attention: La representación del identificador único del comando puede cambiar sin previo aviso.
     """
     (commandType, commandArgs
      ) = CommandsHandler.createVMServerBootCommand(vmServerNameOrIP)
     return self.__commandsDBConnector.addCommand(self.__userID,
                                                  commandType, commandArgs)
 def unregisterVMServer(self, vmServerNameOrIP, isShutDown):
     """
     Borra un servidor de máquinas virtuales
     Argumentos:
         vmServerNameOrIP: el nombre o la IP del servidor a borrar
         isShutDown: si es True, el servidor se apagará inmediatamente. Si es False, esperará a que los usuarios apaguen sus
         máquinas virtuales.
     Devuelve:
         El identificador único del comando.
         @attention: La representación del identificador único del comando puede cambiar sin previo aviso.
     """
     (commandType, commandArgs) = CommandsHandler.createVMServerUnregistrationOrShutdownCommand(True, vmServerNameOrIP, isShutDown)
     return self.__commandsDBConnector.addCommand(self.__userID, commandType, commandArgs)
 def registerVMServer(self, vmServerIP, vmServerPort, vmServerName, isVanillaServer):
     """
     Registra un servidor de máquinas virtuales
     Argumentos:
         vmServerIP: la IP del servidor de máquinas virtuales
         vmServerPort: el puerto en el que escucha
         vmServerName: el nombre del servidor de máquinas virtuales
         isVanillaServer: indica si el servidor de máquinas virtuales se usará preferentemente
             para editar imágenes vanilla o no.
     Devuelve:
         El identificador único del comando.
         @attention: La representación del identificador único del comando puede cambiar sin previo aviso.
     """
     (commandType, commandArgs) = CommandsHandler.createVMServerRegistrationCommand(vmServerIP, vmServerPort, vmServerName, isVanillaServer)
     return self.__commandsDBConnector.addCommand(self.__userID, commandType, commandArgs)
 def shutdownVMServer(self, vmServerNameOrIP, isShutDown):
     """
     Apaga un servidor de máquinas virtuales
     Argumentos:
         vmServerNameOrIP: el nombre o la IP del servidor a borrar
         isShutDown: si es True, el servidor se apagará inmediatamente. Si es False, esperará a que los usuarios apaguen sus
         máquinas virtuales.
     Devuelve:
         El identificador único del comando.
         @attention: La representación del identificador único del comando puede cambiar sin previo aviso.
     """
     (commandType, commandArgs
      ) = CommandsHandler.createVMServerUnregistrationOrShutdownCommand(
          False, vmServerNameOrIP, isShutDown)
     return self.__commandsDBConnector.addCommand(self.__userID,
                                                  commandType, commandArgs)
 def getCommandOutput(self, commandID):
     """
     Devuelve la salida de un comando
     Argumentos:
         commandID: el identificador único del comando
     Devuelve:
         - Si el comando todavía se está ejecutando, se devuelve una tupla vacía.
         - Si el comando se ha terminado de ejecutar, se devuelve un diccionario
           con los datos de su salida.
     """
     if (self.__commandsDBConnector.isRunning(commandID)) :
         return ()
     else :
         result = self.__commandsDBConnector.getCommandOutput(commandID)
         if (result != None) :
             (outputType, outputContent) = result
             result = CommandsHandler.deserializeCommandOutput(outputType, outputContent)
         return result
 def waitForCommandOutput(self, commandID):
     """
     Espera a que un comando termine, devolviendo su salida en caso de que la haya.
     Argumentos:
         commandID: el identificador único del comando
     Devuelve: 
         - None si el comando no tiene salida
         - Un diccionario con los datos de su salida en caso contrario
     @attention: Este método es bloqueante. Si se desea un comportamiento no bloqueante,
     es necesario utilizar el método getCommandOutput.
     """
     while (self.__commandsDBConnector.isRunning(commandID)) :
             sleep(0.1)
     result = self.__commandsDBConnector.getCommandOutput(commandID)
     if result == None :
         return None
     else :
         return CommandsHandler.deserializeCommandOutput(result[0], result[1])
 def getCommandOutput(self, commandID):
     """
     Devuelve la salida de un comando
     Argumentos:
         commandID: el identificador único del comando
     Devuelve:
         - Si el comando todavía se está ejecutando, se devuelve una tupla vacía.
         - Si el comando se ha terminado de ejecutar, se devuelve un diccionario
           con los datos de su salida.
     """
     if (self.__commandsDBConnector.isRunning(commandID)):
         return ()
     else:
         result = self.__commandsDBConnector.getCommandOutput(commandID)
         if (result != None):
             (outputType, outputContent) = result
             result = CommandsHandler.deserializeCommandOutput(
                 outputType, outputContent)
         return result
 def waitForCommandOutput(self, commandID):
     """
     Espera a que un comando termine, devolviendo su salida en caso de que la haya.
     Argumentos:
         commandID: el identificador único del comando
     Devuelve: 
         - None si el comando no tiene salida
         - Un diccionario con los datos de su salida en caso contrario
     @attention: Este método es bloqueante. Si se desea un comportamiento no bloqueante,
     es necesario utilizar el método getCommandOutput.
     """
     while (self.__commandsDBConnector.isRunning(commandID)):
         sleep(0.1)
     result = self.__commandsDBConnector.getCommandOutput(commandID)
     if result == None:
         return None
     else:
         return CommandsHandler.deserializeCommandOutput(
             result[0], result[1])
 def registerVMServer(self, vmServerIP, vmServerPort, vmServerName,
                      isVanillaServer):
     """
     Registra un servidor de máquinas virtuales
     Argumentos:
         vmServerIP: la IP del servidor de máquinas virtuales
         vmServerPort: el puerto en el que escucha
         vmServerName: el nombre del servidor de máquinas virtuales
         isVanillaServer: indica si el servidor de máquinas virtuales se usará preferentemente
             para editar imágenes vanilla o no.
     Devuelve:
         El identificador único del comando.
         @attention: La representación del identificador único del comando puede cambiar sin previo aviso.
     """
     (commandType,
      commandArgs) = CommandsHandler.createVMServerRegistrationCommand(
          vmServerIP, vmServerPort, vmServerName, isVanillaServer)
     return self.__commandsDBConnector.addCommand(self.__userID,
                                                  commandType, commandArgs)
 def _processIncomingPacket(self, packet):
     """
     Procesa un paquete enviado desde el servidor de cluster
     Argumentos:
         packet: el paquete a procesar
     Devuelve:
         Nada
     """
     if (self.__stopped) :
         return
     data = self.__repositoryPacketHandler.readPacket(packet)
     if (data["packet_type"] == PACKET_T.VM_SERVERS_STATUS_DATA) :
         self.__endpointDBConnector.processVMServerSegment(data["Segment"], data["SequenceSize"], data["Data"])
     elif (data["packet_type"] == PACKET_T.VM_DISTRIBUTION_DATA) :
         self.__endpointDBConnector.processVMDistributionSegment(data["Segment"], data["SequenceSize"], data["Data"])
     elif (data["packet_type"] == PACKET_T.ACTIVE_VM_DATA) :
         self.__endpointDBConnector.processActiveVMSegment(data["Segment"], data["SequenceSize"], data["VMServerIP"], data["Data"])
     else :
         l = data["CommandID"].split("|")
         commandID = (int(l[0]), float(l[1]))
         if (data["packet_type"] == PACKET_T.COMMAND_EXECUTED) :
             self.__commandsDBConnector.removeExecutedCommand(commandID)
         else :           
             # El resto de paquetes contienen el resultado de ejecutar comandos => los serializamos y los añadimos
             # a la base de datos de comandos para que los conectores se enteren
             if (data["packet_type"] == PACKET_T.VM_SERVER_BOOTUP_ERROR or 
                 data["packet_type"] == PACKET_T.VM_SERVER_UNREGISTRATION_ERROR or 
                 data["packet_type"] == PACKET_T.VM_SERVER_SHUTDOWN_ERROR) :
                 (outputType, outputContent) = CommandsHandler.createVMServerGenericErrorOutput(
                     data["packet_type"], data["ServerNameOrIPAddress"], data["ErrorMessage"])
             elif (data["packet_type"] == PACKET_T.VM_SERVER_REGISTRATION_ERROR) :
                 (outputType, outputContent) = CommandsHandler.createVMServerRegistrationErrorOutput(
                     data["VMServerIP"], data["VMServerPort"], data["VMServerName"], data["ErrorMessage"])
             elif (data["packet_type"] == PACKET_T.VM_BOOT_FAILURE) :
                 (outputType, outputContent) = CommandsHandler.createVMBootFailureErrorOutput(
                     data["VMID"], data["ErrorMessage"])  
             elif (data["packet_type"] == PACKET_T.VM_CONNECTION_DATA) :
                 (outputType, outputContent) = CommandsHandler.createVMConnectionDataOutput(
                     data["VNCServerIPAddress"], data["VNCServerPort"], data["VNCServerPassword"])
             elif (data["packet_type"] == PACKET_T.DOMAIN_DESTRUCTION_ERROR):
                 (outputType, outputContent) = CommandsHandler.createDomainDestructionErrorOutput(data["ErrorMessage"])
             elif (data["packet_type"] == PACKET_T.VM_SERVER_CONFIGURATION_CHANGE_ERROR) :
                 (outputType, outputContent) = CommandsHandler.createVMServerConfigurationChangeErrorOutput(data["ErrorMessage"])
             self.__commandsDBConnector.addCommandOutput(commandID, outputType, outputContent)
    def processCommands(self):
        """
        Procesa los comandos enviados desde los conectores
        Argumentos:
            Ninguno
        Devuelve:
            Nada
        """
        while not self.__stopped:
            commandData = self.__commandsDBConnector.popCommand()
            if (commandData == None):
                sleep(0.1)
            else:
                (commandID, commandType, commandArgs) = commandData
                parsedArgs = CommandsHandler.deserializeCommandArgs(
                    commandType, commandArgs)
                if (commandType != COMMAND_TYPE.HALT):
                    serializedCommandID = "{0}|{1}".format(
                        commandID[0], commandID[1])
                    if (commandType == COMMAND_TYPE.BOOTUP_VM_SERVER):
                        packet = self.__repositoryPacketHandler.createVMServerBootUpPacket(
                            parsedArgs["VMServerNameOrIP"],
                            serializedCommandID)
                    elif (commandType == COMMAND_TYPE.REGISTER_VM_SERVER):
                        packet = self.__repositoryPacketHandler.createVMServerRegistrationPacket(
                            parsedArgs["VMServerIP"],
                            parsedArgs["VMServerPort"],
                            parsedArgs["VMServerName"],
                            parsedArgs["IsVanillaServer"], serializedCommandID)
                    elif (commandType ==
                          COMMAND_TYPE.UNREGISTER_OR_SHUTDOWN_VM_SERVER):
                        packet = self.__repositoryPacketHandler.createVMServerUnregistrationOrShutdownPacket(
                            parsedArgs["VMServerNameOrIP"], parsedArgs["Halt"],
                            parsedArgs["Unregister"], serializedCommandID)
                    elif (commandType == COMMAND_TYPE.VM_BOOT_REQUEST):
                        packet = self.__repositoryPacketHandler.createVMBootRequestPacket(
                            parsedArgs["VMID"], parsedArgs["UserID"],
                            serializedCommandID)
                    elif (commandType == COMMAND_TYPE.DESTROY_DOMAIN):
                        packet = self.__repositoryPacketHandler.createDomainDestructionPacket(
                            parsedArgs["DomainID"], serializedCommandID)
                    elif (commandType ==
                          COMMAND_TYPE.VM_SERVER_CONFIGURATION_CHANGE):
                        packet = self.__repositoryPacketHandler.createVMServerConfigurationChangePacket(
                            parsedArgs["VMServerNameOrIPAddress"],
                            parsedArgs["NewServerName"],
                            parsedArgs["NewServerIPAddress"],
                            parsedArgs["NewServerPort"],
                            parsedArgs["NewVanillaImageEditionBehavior"],
                            serializedCommandID)
                    errorMessage = self.__manager.sendPacket(
                        self.__clusterServerIP, self.__clusterServerPort,
                        packet)
                    if (errorMessage != None):
                        # Error al enviar el paquete => el comando no se podrá ejecutar => avisar a la web
                        (outputType, outputContent
                         ) = CommandsHandler.createConnectionErrorOutput()
                        self.__commandsDBConnector.addCommandOutput(
                            commandID, outputType, outputContent)

                else:
                    self.__stopped = True
                    self.__haltVMServers = parsedArgs["HaltVMServers"]
 def _processIncomingPacket(self, packet):
     """
     Procesa un paquete enviado desde el servidor de cluster
     Argumentos:
         packet: el paquete a procesar
     Devuelve:
         Nada
     """
     if (self.__stopped):
         return
     data = self.__repositoryPacketHandler.readPacket(packet)
     if (data["packet_type"] == PACKET_T.VM_SERVERS_STATUS_DATA):
         self.__endpointDBConnector.processVMServerSegment(
             data["Segment"], data["SequenceSize"], data["Data"])
     elif (data["packet_type"] == PACKET_T.VM_DISTRIBUTION_DATA):
         self.__endpointDBConnector.processVMDistributionSegment(
             data["Segment"], data["SequenceSize"], data["Data"])
     elif (data["packet_type"] == PACKET_T.ACTIVE_VM_DATA):
         self.__endpointDBConnector.processActiveVMSegment(
             data["Segment"], data["SequenceSize"], data["VMServerIP"],
             data["Data"])
     else:
         l = data["CommandID"].split("|")
         commandID = (int(l[0]), float(l[1]))
         if (data["packet_type"] == PACKET_T.COMMAND_EXECUTED):
             self.__commandsDBConnector.removeExecutedCommand(commandID)
         else:
             # El resto de paquetes contienen el resultado de ejecutar comandos => los serializamos y los añadimos
             # a la base de datos de comandos para que los conectores se enteren
             if (data["packet_type"] == PACKET_T.VM_SERVER_BOOTUP_ERROR
                     or data["packet_type"]
                     == PACKET_T.VM_SERVER_UNREGISTRATION_ERROR
                     or data["packet_type"]
                     == PACKET_T.VM_SERVER_SHUTDOWN_ERROR):
                 (outputType, outputContent
                  ) = CommandsHandler.createVMServerGenericErrorOutput(
                      data["packet_type"], data["ServerNameOrIPAddress"],
                      data["ErrorMessage"])
             elif (data["packet_type"] ==
                   PACKET_T.VM_SERVER_REGISTRATION_ERROR):
                 (outputType, outputContent
                  ) = CommandsHandler.createVMServerRegistrationErrorOutput(
                      data["VMServerIP"], data["VMServerPort"],
                      data["VMServerName"], data["ErrorMessage"])
             elif (data["packet_type"] == PACKET_T.VM_BOOT_FAILURE):
                 (outputType, outputContent
                  ) = CommandsHandler.createVMBootFailureErrorOutput(
                      data["VMID"], data["ErrorMessage"])
             elif (data["packet_type"] == PACKET_T.VM_CONNECTION_DATA):
                 (outputType, outputContent
                  ) = CommandsHandler.createVMConnectionDataOutput(
                      data["VNCServerIPAddress"], data["VNCServerPort"],
                      data["VNCServerPassword"])
             elif (data["packet_type"] == PACKET_T.DOMAIN_DESTRUCTION_ERROR
                   ):
                 (outputType, outputContent
                  ) = CommandsHandler.createDomainDestructionErrorOutput(
                      data["ErrorMessage"])
             elif (data["packet_type"] ==
                   PACKET_T.VM_SERVER_CONFIGURATION_CHANGE_ERROR):
                 (
                     outputType, outputContent
                 ) = CommandsHandler.createVMServerConfigurationChangeErrorOutput(
                     data["ErrorMessage"])
             self.__commandsDBConnector.addCommandOutput(
                 commandID, outputType, outputContent)
 def changeVMServerConfiguration(self, serverNameOrIPAddress, newName, newIPAddress, newPort, 
                                 newVanillaImageEditionBehavior):
     (commandType, commandArgs) = CommandsHandler.createVMServerConfigurationChangeCommand(serverNameOrIPAddress, 
         newName, newIPAddress, newPort, newVanillaImageEditionBehavior)
     return self.__commandsDBConnector.addCommand(self.__userID, commandType, commandArgs)