示例#1
0
    def run(self):
        if not hasattr(self.context, "topology") or type(
                self.context.topology) != dissomniag.model.Topology:
            self.job.trace(
                "DeleteTopology: In Context missing topology object.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "In Context missing topology object.")
        if ((self.context.topology.generatedNetworks != None
             and len(self.context.topology.generatedNetworks) != 0)
                or (self.context.topology.vms != None
                    and len(self.context.topology.vms) != 0)):
            self.job.trace(
                "Topology %s cannot be deleted securely: Make sure that all networks and all VM's of the Topology are deleted."
            )
            raise dissomniag.taskManager.UnrevertableFailure(
                "Not all VM's or Nets are deleted in Topology")

        try:
            session = dissomniag.Session()
            session.delete(self.context.topology)
            dissomniag.saveCommit(session)
            self.context.topology = None
        except Exception, e:
            raise dissomniag.taskManager.UnrevertableFailure(
                "Cannot delete Topology. SqlalchemyError: %s" % e)
示例#2
0
 def implementation(self, *args):
     sys.stdout = self.terminal
     sys.stderr = self.terminal
     
     parser = argparse.ArgumentParser(description = 'Stop a job.', prog = args[0])
     parser.add_argument("jobId", action = "store")
     options = parser.parse_args(list(args[1:]))
     
     jobId = int(options.jobId)
     job = taskManager.Dispatcher.getJob(user = self.user, jobId = jobId)
     if job:
         if not self.user.isAdmin and self.user != job.user:
             self.printError("You are not allowed to delete this Job. Go away.")
             return
         else: 
             taskManager.Dispatcher.cancelJob(user = self.user, jobId = jobId)
             self.printSuccess("Job Cancel Request sended")
             return
     else:
         self.printError("JobId is not valid, or Job is no longer handled by the Dispatcher.")
     
     session = dissomniag.Session()
     try:
         job = session.query(taskManager.jobs.JobInfo).filter(taskManager.jobs.JobInfo.id == jobId).filter(taskManager.jobs.JobInfo.state.in_(taskManager.jobs.JobStates.getRunningStates())).one()
         job.state = taskManager.jobs.JobStates.CANCELLED
         dissomniag.saveCommit(session)
         self.printInfo("Job canceled without using ")
     except (NoResultFound, MultipleResultsFound):
         self.printError("Could also not cancel Job in other Job List")
示例#3
0
    def run(self):
        if not hasattr(self.context, "app") or type(
                self.context.app) != dissomniag.model.App:
            self.job.trace("DeleteAppFinally: In Context missing app object.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "In Context missing app object.")

        if self.context.app.AppLiveCdRelations != []:
            self.multiLog("Cannot delete an app with LiveCd Relations!", log)
            raise dissomniag.taskManager.TaskFailed(
                "Cannot delete an app with LiveCd Relations!")

        self.deleted = True
        pathToRepository = os.path.join(
            dissomniag.config.git.pathToGitRepositories,
            ("%s.git") % self.context.app.name)
        with dissomniag.rootContext():
            try:
                shutil.rmtree(pathToRepository)
            except Exception as e:
                self.multiLog(
                    "Cannot delete local Repository %s %s" %
                    (str(e), pathToRepository), log)

        session = dissomniag.Session()
        session.delete(self.context.app)
        dissomniag.saveCommit(session)

        return dissomniag.taskManager.TaskReturns.SUCCESS
示例#4
0
 def getAdministrativeUser(self):
     session = dissomniag.Session()
     user = None
     try:
         user = session.query(dissomniag.auth.User).filter(
             dissomniag.auth.User.username == self.systemUserName).one()
     except MultipleResultsFound:
         one = False
         users = session.query(dissomniag.auth.User).filter(
             dissomniag.auth.User.username == self.systemUserName).all()
         for myUser in users:
             if one == False:
                 user = myUser
                 one = True
                 continue
             else:
                 session.delete(myUser)
     except NoResultFound:
         password = self.generateRandomPassword(length=40)
         user = dissomniag.auth.User(self.systemUserName,
                                     password=password,
                                     isAdmin=True,
                                     loginRPC=False,
                                     loginSSH=False,
                                     loginManhole=False,
                                     isHtpasswd=False)
         session.add(user)
         dissomniag.saveCommit(session)
     finally:
         return user
示例#5
0
 def __init__(self, user, ipAddrOrNet, node = None, isDhcpAddress = False, net = None):
     session = dissomniag.Session()
     
     if not isinstance(ipAddrOrNet, (ipaddr.IPv4Network, ipaddr.IPv6Network)):
         ipAddrOrNet = ipaddr.IPNetwork(ipAddrOrNet)
     
     if node:
         self.node = node
     
     self.isDhcpAddress = isDhcpAddress
     
     self.addr = str(ipAddrOrNet.ip)
     if (ipAddrOrNet.version == 4):
         self.isV6 = False
     elif (ipAddrOrNet.version == 6):
         self.isV6 = True
     
     if (ipAddrOrNet.prefixlen < ipAddrOrNet.max_prefixlen) and not net:
         found = False
         try:
             networks = session.query(Network).filter(Network.netAddress == str(ipAddrOrNet.network)).filter(Network.netMask == str(ipAddrOrNet.netmask)).all()
             for network in networks:
                 if node in network.nodes:
                     found = True # Net is associated with actual node, there is no need to create a new Net 
         except NoResultFound:
             found = False
         finally:
             if found == False:
                 self.network = Network(user, ipAddrOrNet, node)
     elif isinstance(net, (dissomniag.model.Network, dissomniag.model.generatedNetwork)):
         self.network = net
     session.add(self)
     dissomniag.saveCommit(session)
示例#6
0
 def __init__(self, user, commonName, setMyUuid = None, maintainanceIP = None,
              sshKey = None, administrativeUserName = None,
              utilityFolder = None, state = None,
              parseLocalInterfaces = False):
     self.commonName = commonName
     if setMyUuid == None:
         self.uuid = str(uuid.uuid4())
     else:
         self.uuid = uuid
         
     if state != None and NodeState.checkIn(state):
         self.state = state
     else:
         self.state = NodeState.NOT_CREATED
     session = dissomniag.Session()
     session.add(self)
     dissomniag.saveCommit(session)
     
     if maintainanceIP != None:
         self.addIp(user, maintainanceIP, isMaintainanceIP = True)
     
     if sshKey != None and isinstance(sshKey, SSHNodeKey):
         self.sshKey = sshKey
     
     if administrativeUserName != None:
         self.administrativeUserName = administrativeUserName
         
     if utilityFolder != None:
         self.utilityFolder = utilityFolder
     
     if parseLocalInterfaces:
         self.parseLocalInterfaces(user)
     
     if maintainanceIP == None and len(self.ipAddresses) > 0:
         self.maintainanceIP = self.ipAddresses[0]
示例#7
0
 def __init__(self, context, description, user = None, group = None, target = None, name = None,
              args = (), kwargs = None, verbose = None):
     """
     Constructor
     """
     threading.Thread.__init__(self, group = group, target = target,
                                   name = name, verbose = verbose)
     session = dissomniag.Session()
     self.state = JobStates.QUEUED
     self.infoObj = JobInfo(description = description, state = self.state, user = user)
     session.add(self.infoObj)
     dissomniag.saveCommit(session)
     dissomniag.saveFlush(session)
     self.id = self.infoObj.id
     if user != None:
         self.user = user
     else:
         self.user = None
     
     
     self.context = context
     self.description = description
     self.taskList = []
     self.currentTaskId = 0
     self.runningLock = threading.RLock()
     self.writeProperty = threading.RLock()
     self.dispatcher = None
     
     self.infoObj = None
示例#8
0
 def run(self):
     if not hasattr(self.context, "liveCd"):
         self.multiLog("deleteLiveCd: No LiveCd in Context", log)
         raise dissomniag.taskManager.TaskFailed("deleteLiveCd: No LiveCd in Context")
     
     # 1. Delete Local Image
     self.multiLog("Delete local LiveCd image.", log)
     try:
         shutil.rmtree(self.context.liveCd.vm.getLocalUtilityFolder(self.job.getUser()))
     except OSError:
         self.multiLog("Cannot delete local LiveCd image.", log)
         
     # 2. Delete Remote Image
     cmd = "rm -rf %s" % self.context.liveCd.vm.getRemoteUtilityFolder(self.job.getUser())
     sshCmd = dissomniag.utils.SSHCommand(cmd, \
                                          self.context.liveCd.vm.host.getMaintainanceIP(), \
                                          self.context.liveCd.vm.host.administrativeUserName)
     ret, output = sshCmd.callAndGetOutput()
     self.multiLog("Delete LiveCd image remote. ret: %d, output: %s" % (ret, output))
     
     session = dissomniag.Session()
 
     try:
         session.delete(self.context.liveCd)
         dissomniag.saveCommit(session)
     except Exception:
         failed = True
     else:
         failed = False
     
     if not failed:
         return dissomniag.taskManager.TaskReturns.SUCCESS
     else:
         return dissomniag.taskManager.TaskReturns.FAILED_BUT_GO_AHEAD
示例#9
0
文件: VM.py 项目: swallat/DiSSOmniaG
 def changeState(self, nextState):
     if not dissomniag.model.NodeState.checkIn(nextState):
         raise TypeError()
     else:
         session = dissomniag.Session()
         if nextState == dissomniag.model.NodeState.NOT_CREATED:
             self.runningState = self.notCreatedState
             self.state = dissomniag.model.NodeState.NOT_CREATED
         elif nextState == dissomniag.model.NodeState.CREATED:
             self.runningState = self.createdState
             self.state = dissomniag.model.NodeState.CREATED
         elif nextState == dissomniag.model.NodeState.PREPARED:
             self.runningState = self.preparedState
             self.state = dissomniag.model.NodeState.PREPARED
         elif nextState == dissomniag.model.NodeState.PREPARE_ERROR:
             self.runningState = self.prepareErrorState
             self.state = dissomniag.model.NodeState.PREPARE_ERROR
         elif nextState == dissomniag.model.NodeState.DEPLOYED:
             self.runningState = self.deployedState
             self.state = dissomniag.model.NodeState.DEPLOYED
         elif nextState == dissomniag.model.NodeState.DEPLOY_ERROR:
             self.runningState = self.deployErrorState
             self.state = dissomniag.model.NodeState.DEPLOY_ERROR
         elif nextState == dissomniag.model.NodeState.RUNTIME_ERROR:
             self.runningState = self.runtimeErrorState
             self.state = dissomniag.model.NodeState.RUNTIME_ERROR
         dissomniag.saveCommit(session)
示例#10
0
 def __init__(self, user, node, name = None, mac = None):
     session = dissomniag.Session()
     self.node = node
     self.macAddress = mac
     self.name = name
     session.add(self)
     dissomniag.saveCommit(session)
示例#11
0
文件: App.py 项目: swallat/DiSSOmniaG
 def __init__(self, app, liveCd):
     self.app = app
     self.liveCd = liveCd
     
     session = dissomniag.Session()
     session.add(self)
     dissomniag.saveCommit(session)
示例#12
0
    def run(self):
        if not hasattr(self.context, "vm") or not isinstance(
                self.context.vm, dissomniag.model.VM):
            self.job.trace("udateLiveClientVM: In Context missing vm object.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "In Context missing vm object.")
        try:
            proxy = xmlrpclib.ServerProxy(self.context.vm.getRPCUri(self.user))
        except dissomniag.NoMaintainanceIp as e:
            self.job.trace(
                "No MaintainanceIp for VM available. Wait until it has fully started."
            )
            return dissomniag.taskManager.TaskReturns.FAILED_BUT_GO_AHEAD
        except Exception as e:
            self.job.trace(
                "General RPC Error. Wait until Vm has fully started.")

        try:
            xml = proxy.update(
                self.context.vm.liveCd.getInfoXml(self.job.getUser()))
            self.context.vm.recvUpdateLiveClient(self.job.getUser(), xml)
        except Exception as e:
            self.job.trace("Could not gather informations about a VM.")
            session = dissomniag.Session()
            self.context.vm.lastSeenClient = None
            dissomniag.saveCommit(session)
示例#13
0
 def reset(self, job):
     returnMe = self.stop(job)
     session = dissomniag.Session()
     self.vm.lastSeenCient = None
     dissomniag.saveCommit(session)
     self.vm.changeState(dissomniag.model.NodeState.DEPLOYED)
     return returnMe
示例#14
0
 def _setState(self, state):
     with self.writeProperty:
         session = dissomniag.Session()
         self._reFetchInfoObj()
         self.state = state
         self.infoObj.state = state
         dissomniag.saveCommit(session)
示例#15
0
    def run(self):
        if (not hasattr(self.context, "node")
                or not isinstance(self.context.node, dissomniag.model.VM)
                or not hasattr(self.context, "vm")
                or not isinstance(self.context.vm, dissomniag.model.VM)
                or self.context.node != self.context.vm):
            self.job.trace("DeleteVM: In Context missing vm object.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "In Context missing vm object.")

        vm = self.context.vm
        self.job.trace("IN DELETE")

        if (vm.liveCd != None or (len(vm.interfaces) != 0)
                or (len(vm.ipAddresses) != 0)):
            self.job.trace(
                "VM %s cannot be deleted securely: Make sure that the LiveCD, all Interfaces and all IP Addresses of the VM are deleted."
                % vm.commonName)
            raise dissomniag.taskManager.UnrevertableFailure(
                "Not all IPs, Interfaces or the LiveCD are deleted of the VM.")

        try:
            session = dissomniag.Session()
            session.delete(vm.sshKey)
            session.delete(vm)
            dissomniag.saveCommit(session)
            self.context.vm = None
            self.context.node = None
        except Exception, e:
            raise dissomniag.taskManager.UnrevertableFailure(
                "Cannot delete VM. SqlalchemyError: %s" % e)
示例#16
0
    def deleteTopology(user, topo):
        if topo == None or type(topo) != Topology:
            return False
        topo.authUser(user)
        
        #1. Delete VM's
        for vm in topo.vms:
            dissomniag.model.VM.deleteVM(user, vm)
            
        #2. Delete Networks's
        for net in topo.generatedNetworks:
            dissomniag.model.generatedNetwork.deleteNetwork(user, net)
            
        session = dissomniag.Session()
        #3. Delete General Network's
        for net in topo.generalNetworks:
            session.delete(net)

        dissomniag.saveCommit(session)
        
        context = dissomniag.taskManager.Context()
        context.add(topo, "topology") 
        
        job = dissomniag.taskManager.Job(context = context, description = "Delete Topology", user = user)
        #3. Delete Connections
        job.addTask(dissomniag.tasks.DeleteVMsOfTopology())
        job.addTask(dissomniag.tasks.DeleteNetworksOfTopology())
        
        #4. Delete Topology
        job.addTask(dissomniag.tasks.DeleteTopology())
        
        dissomniag.taskManager.Dispatcher.addJob(user, job)
        return True
示例#17
0
 def __init__(self, user, node, name=None, mac=None):
     session = dissomniag.Session()
     self.node = node
     self.macAddress = mac
     self.name = name
     session.add(self)
     dissomniag.saveCommit(session)
示例#18
0
文件: App.py 项目: swallat/DiSSOmniaG
 def createRelation(user, app, liveCd):
     if app.authUser(user) and liveCd.authUser(user):
         try:
             session = dissomniag.Session()
             rels = session.query(dissomniag.model.AppLiveCdRelation).filter(dissomniag.model.AppLiveCdRelation.liveCd == liveCd).filter(dissomniag.model.AppLiveCdRelation.app == app).one()
         except NoResultFound:
             rel = AppLiveCdRelation(app, liveCd)
             context = dissomniag.taskManager.Context()
             context.add(app, "app")
             context.add(liveCd, "liveCd")
             job = dissomniag.taskManager.Job(context, "Create initially an AppLiveCdRelation", user)
             job.addTask(dissomniag.tasks.AddAppBranch())
             job.addTask(dissomniag.tasks.GitPushAdminRepo())
             if liveCd.vm.state == dissomniag.model.NodeState.CREATED:
                 job.addTask(dissomniag.tasks.addAppOnRemote())
             dissomniag.taskManager.Dispatcher.addJobSyncronized(user, dissomniag.GitEnvironment(), job)
             return rel
         except MultipleResultsFound:
             first = True
             rels = session.query(dissomniag.model.AppLiveCdRelation).filter(dissomniag.model.AppLiveCdRelation.liveCd == liveCd).filter(dissomniag.model.AppLiveCdRelation.app == app).all()
             for rel in rels:
                 if first:
                     first = False
                     continue
                 session.delete(rel)
             dissomniag.saveCommit(session)
         else:
             return rels
示例#19
0
    def stop(self, job):
        session = dissomniag.Session()
        self.vm.lastSeenCient = None
        dissomniag.saveCommit(session)
        try:
            con = libvirt.open(str(self.vm.host.qemuConnector))
        except libvirt.libvirtError:
            self.vm.changeState(dissomniag.model.NodeState.DEPLOY_ERROR)
            raise dissomniag.taskManager.TaskFailed(
                "Could Not Connect to Libvirt Host!")

        try:
            vm = con.lookupByName(self.vm.commonName)
        except libvirt.libvirtError:
            self.multiLog("destroyVMOnHost: Could not find VM on host.", job,
                          log)
        else:
            try:
                vm.destroy()
            except libvirt.libvirtError:
                self.multiLog(
                    "destroyVMOnHost: could not destroy or undefine vm", job,
                    log)
                self.vm.changeState(dissomniag.model.NodeState.DEPLOY_ERROR)
                return dissomniag.taskManager.TaskReturns.FAILED_BUT_GO_AHEAD

        self.vm.changeState(dissomniag.model.NodeState.DEPLOYED)
        return dissomniag.taskManager.TaskReturns.SUCCESS
示例#20
0
 def reset(self, job):
     returnMe = self.stop(job)
     session = dissomniag.Session()
     self.vm.lastSeenCient = None
     dissomniag.saveCommit(session)
     self.vm.changeState(dissomniag.model.NodeState.DEPLOYED)
     return returnMe
示例#21
0
 def implementation(self, *args):
     sys.stdout = self.terminal
     sys.stderr = self.terminal
     
     if not self.user.isAdmin:
         self.printError("Only Admin Users can modify Hosts!")
     
     parser = argparse.ArgumentParser(description = "Modify a Host", prog = args[0])
     parser.add_argument("-i", "--ipAddress", dest = "ipAddress", action = "store", default = None)
     parser.add_argument("-u", "--adminUser", dest = "adminUser", action = "store", default = None)
     parser.add_argument("-b", "--bridgeName", dest = "bridgeName", action = "store", default = None)
     parser.add_argument("commonName", action = "store")
     
     options = parser.parse_args(args[1:])
     
     session = dissomniag.Session()
     host = None
     try:
         host = session.query(dissomniag.model.Host).filter(dissomniag.model.Host.commonName == str(options.commonName)).one()
     except (NoResultFound, MultipleResultsFound):
         self.printError("The Host you have entered is not known or valid.")
         return
     if options.ipAddress != None:
         if not dissomniag.model.IpAddress.checkValidIpAddress(options.ipAddress):
             self.printError("The IpAddress is not valid.")
         else:
             host.modMaintainandceIP(self.user, str(options.ipAddress), deleteOld = True)
     
     if options.adminUser != None:
         host.modAdministrativeUserName(self.user, str(options.adminUser))
     
     if options.bridgeName != None:
         host.modBridgedInterfaceName(self.user, str(options.bridgeName))
     
     dissomniag.saveCommit(session)
示例#22
0
 def cleanUpJobDbViaUser(user, userName = None):
     """
     Delete old Jobs in Db via userName
     """
     session = dissomniag.Session()
     if userName != None:
         try:
             otherUser = session.query(dissomniag.auth.User).filter(dissomniag.auth.User.username == str(userName)).one()
         except (NoResultFound, MultipleResultsFound):
             otherUser = None
     else:
         otherUser = None
         
     try:
         if user.isAdmin and userName != None and otherUser != None:
             jobs = session.query(JobInfo).filter(JobInfo.user == otherUser).filter(JobInfo.state.in_(JobStates.getFinalStates())).all()
         elif userName == None:
             jobs = session.query(JobInfo).filter(JobInfo.user == user).filter(JobInfo.state.in_(JobStates.getFinalStates())).all()
         else:
             return False
     except NoResultFound:
         return False
     
     for job in jobs:
         session.delete(job)
     dissomniag.saveCommit(session)
     return True
示例#23
0
 def addInterface(self, user, name, mac = None, ipAddresses = [], net = None):
     """
     This method adds an interface to the current node with the name = "name".
     If no Mac Address is provided, a new one is generated.
     By adding a list of IPAddresses it is possible to assign IpAddresses to an interface.
     
     If the provided Mac Adresss is not valid this method raises an NoMacError(),
     which can be found in dissomniag.utils.Exceptions()
     """
     self.authUser(user)
     
     session = dissomniag.Session()
     interface = None
     if type(name) != str:
         raise dissomniag.NotStringError()
     if mac == None:
         mac = Interface.getRandomMac()
     # Raises NoValidMac on Mac Failure
     Interface.checkValidMac(mac)
     
     try:
         interface = session.query(Interface).filter(Interface.macAddress == mac).filter(Interface.node == self).one()
     except NoResultFound:
         interface = None
     except MultipleResultsFound:
         interfaces = session.query(Interface).filter(Interface.macAddress == mac).filter(Interface.node == self).all()
         one = False
         name = False
         for inter in interfaces:
             if not one:
                 interface = inter
                 if interface.name == name:
                     name = True
                 one = True
             elif one and not name:
                 if inter.name == name:
                     Interface.deleteInterface(user, inter, isAdministrative = True)
                     interface = inter
                     name = True
             elif one and name:
                 Interface.deleteInterface(user, inter, isAdministrative = True)             
     finally:
         if interface == None:
             interface = Interface(user, self, name, mac)
             self.interfaces.append(interface)
             
         for ipAddr in ipAddresses:
             interface.addIp(user, ipAddr, net = net)     
         try:
             equalNamedInterfaces = session.query(Interface).filter(Interface.name == name).filter(Interface.node == self).all()
             for namedInterface in equalNamedInterfaces:
                 if namedInterface.macAddress != mac:
                     #Delete all Equally named Interfaces
                     Interface.deleteInterface(user, namedInterface, isAdministrative = True)
         except NoResultFound:
             pass
         
         dissomniag.saveCommit(session)
         return interface           
示例#24
0
 def cancelBeforeStartup(self):
     with self.runningLock:
         session = dissomniag.Session()
         self._reFetchInfoObj()
         self.state = JobStates.CANCELLED
         self.infoObj.state = self.state
         dissomniag.saveCommit(session)
         self.infoObj = None
示例#25
0
 def _getStatePrivate(self):
     self._reFetchInfoObj()
     if self.state != self.infoObj.state:
         session = dissomniag.Session()
         if self.state == JobStates.CANCELLED:
             self.trace("### JOB CANCELLED ###")
         self.infoObj.state = self.state
         dissomniag.saveCommit(session)
     return self.state
示例#26
0
 def changeState(self, user, state):
     self.authUser(user)
     
     session = dissomniag.Session()
     if not NodeState.checkIn(state):
         return False
     else:
         self.state = state
     dissomniag.saveCommit(session)
示例#27
0
 def modBridgedInterfaceName(self, user, newName):
     self.authUser(user)
     if len(newName) > 10:
         return False
     else:
         session = dissomniag.Session()
         self.bridgedInterfaceName = newName
         dissomniag.saveCommit(session)
         return True
示例#28
0
 def _revertFrom(self, taskId):
     """
     Revert performed Tasks.
     """
     with self.writeProperty:
         if not dissomniag.config.dispatcher.revertBeforeCancel:
             if self._getStatePrivate() == JobStates.CANCELLED:
                 """
                 Check if a cancell request occured
                 """
                 self.trace("Job %s cancelled while executing taskId: %s" % \
                             (str(self.id), str(self.currentTaskId)))
                 log.info("Job %s cancelled while executing taskId: %s" % \
                             (str(self.id), str(self.currentTaskId)))
                 raise tasks.TaskFailed()
         
         if self._getStatePrivate() != JobStates.CANCELLED:   
             self._setState(JobStates.REVERTING)
         session = dissomniag.Session()
         dissomniag.saveCommit(session)
     
     lastFailed = False
     
     for i, task in zip(range(taskId, -1, -1), reversed(self.taskList[:(taskId + 1)])):
         
         if not dissomniag.config.dispatcher.revertBeforeCancel:
             if self._getStatePrivate() == JobStates.CANCELLED:
                 """
                 Check if a cancell request occured
                 """
                 self.trace("Job %s cancelled while executing taskId: %s" % \
                             (str(self.id), str(self.currentTaskId)))
                 log.INFO("Job %s cancelled while executing taskId: %s" % \
                             (str(self.id), str(self.currentTaskId)))
                 raise tasks.TaskFailed()
         
         self.currentTaskId = i
         
         try:
             
             param = task.callRevert(self, self.context, lastFailed)
             
         except NotImplementedError:
             self.trace("In Job %s the Task %s failed reverting." % \
                         (str(self.id), str(self.currentTaskId)))
             log.INFO("In Job %s the Task %s failed reverting." % \
                         (str(self.id), str(self.currentTaskId)))
             raise tasks.UnrevertableFailure()
         else:
         
             if param == tasks.TaskReturns.FAILED_BUT_GO_AHEAD:
                 lastFailed = True
                 self.trace("In Job %s the Task %s failed without stopping" % \
                         (str(self.id), str(self.currentTaskId)))
             else: # param == task.TaskReturns.SUCCESS
                 lastFailed = False
示例#29
0
    def implementation(self, *args):
        sys.stdout = self.terminal
        sys.stderr = self.terminal

        parser = argparse.ArgumentParser(description="Delete a user",
                                         prog=args[0])
        parser.add_argument(
            "username",
            action="store",
            help="Enter the username of the User you want to delete.")
        options = parser.parse_args(args[1:])

        if not self.user.isAdmin:
            self.printError(
                "Permission denied: Only Admin users are allowed to delete a users!"
            )
            return

        if options.username == self.user.username:
            self.printError("Permission denied: You cannot delete yourself!")
            return

        if options.username == dissomniag.config.htpasswd.adminUser:
            self.printError(
                "Permission denied: You cannot delete the default admin user!")
            return

        if options.username == dissomniag.Identity.systemUserName:
            self.printError(
                "Permission denied: You cannot delete the system user!")
            return

        session = dissomniag.Session()

        try:
            user = session.query(User).filter(
                User.username == options.username).one()
            if user.isMaintain:
                self.printError(
                    "Permission denied: You cannot delete a maintainance User!"
                )
                return
            session.delete(user)
            dissomniag.saveCommit(session)
            dissomniag.saveFlush(session)
        except NoResultFound:
            self.printError("User %s does not exists." % options.username)
            return
        except Exception:
            self.printError("Unspecified Error")
            return

        self.printSuccess("User %s successful deleted." % options.username)
示例#30
0
    def implementation(self, *args):
        sys.stdout = self.terminal
        sys.stderr = self.terminal

        if not self.user.isAdmin:
            self.printError("Only Admin Users can modify Hosts!")

        parser = argparse.ArgumentParser(description="Modify a Host",
                                         prog=args[0])
        parser.add_argument("-i",
                            "--ipAddress",
                            dest="ipAddress",
                            action="store",
                            default=None)
        parser.add_argument("-u",
                            "--adminUser",
                            dest="adminUser",
                            action="store",
                            default=None)
        parser.add_argument("-b",
                            "--bridgeName",
                            dest="bridgeName",
                            action="store",
                            default=None)
        parser.add_argument("commonName", action="store")

        options = parser.parse_args(args[1:])

        session = dissomniag.Session()
        host = None
        try:
            host = session.query(dissomniag.model.Host).filter(
                dissomniag.model.Host.commonName == str(
                    options.commonName)).one()
        except (NoResultFound, MultipleResultsFound):
            self.printError("The Host you have entered is not known or valid.")
            return
        if options.ipAddress != None:
            if not dissomniag.model.IpAddress.checkValidIpAddress(
                    options.ipAddress):
                self.printError("The IpAddress is not valid.")
            else:
                host.modMaintainandceIP(self.user,
                                        str(options.ipAddress),
                                        deleteOld=True)

        if options.adminUser != None:
            host.modAdministrativeUserName(self.user, str(options.adminUser))

        if options.bridgeName != None:
            host.modBridgedInterfaceName(self.user, str(options.bridgeName))

        dissomniag.saveCommit(session)
示例#31
0
    def run(self):
        if not hasattr(self.context, "app") or type(
                self.context.app) != dissomniag.model.App:
            self.job.trace(
                "DeleteAppLiveCdRelation: In Context missing app object.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "In Context missing app object.")

        if not hasattr(self.context, "liveCd") or type(
                self.context.liveCd) != dissomniag.model.LiveCd:
            self.job.trace(
                "DeleteAppLiveCdRelation: In Context missing liveCd object.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "In Context missing liveCd object.")

        session = dissomniag.Session()
        try:
            appLiveCdRel = session.query(
                dissomniag.model.AppLiveCdRelation).filter(
                    dissomniag.model.AppLiveCdRelation.app == self.context.app
                ).filter(dissomniag.model.AppLiveCdRelation.liveCd ==
                         self.context.liveCd).one()
        except NoResultFound:
            self.job.trace(
                "DeleteAppLiveCdRelation: No Relation object found.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "No Relation object found.")
        except MultipleResultsFound:
            appLiveCdRel = appLiveCdRel[0]

        pathToRepository = os.path.join(
            dissomniag.config.git.pathToGitRepositories,
            ("%s.git") % appLiveCdRel.app.name)
        branchName = self.context.liveCd.vm.commonName

        with dissomniag.rootContext():
            try:
                repo = git.Repo(pathToRepository)
                if branchName in repo.heads:
                    #repo.delete_head(branchName)
                    repo.git.branch("-D", branchName)
            except Exception as e:
                self.multiLog("Cannot delete branch in Revert %s" % str(e),
                              log)
                raise dissomniag.taskManager.TaskFailed(
                    "Cannot delete branch in Revert %s" % str(e))

        self.deleted = True
        session = dissomniag.Session()
        session.delete(appLiveCdRel)
        dissomniag.saveCommit(session)
        return dissomniag.taskManager.TaskReturns.SUCCESS
示例#32
0
文件: App.py 项目: swallat/DiSSOmniaG
 def __init__(self, user, name):
     self.users.append(user)
     self.name = name
     
     session = dissomniag.Session()
     session.add(self)
     dissomniag.saveCommit(session)
     context = dissomniag.taskManager.Context()
     context.add(self, "app")
     job = dissomniag.taskManager.Job(context, "Create initially an App", user)
     job.addTask(dissomniag.tasks.GitPushAdminRepo())
     job.addTask(dissomniag.tasks.MakeInitialCommit())
     dissomniag.taskManager.Dispatcher.addJobSyncronized(user, dissomniag.GitEnvironment(), job)
示例#33
0
文件: App.py 项目: swallat/DiSSOmniaG
 def updateInfo(self, user, state, log = None):
     session = dissomniag.Session()
     
     self.authUser(user)
     self.lastSeen = datetime.datetime.now()
     if AppState.isValid(state):
         self.state = state
         
     if log == None or not isinstance(log, str):
         self.log = ""
     else:
         self.log = log
     dissomniag.saveCommit(session)
示例#34
0
文件: VM.py 项目: swallat/DiSSOmniaG
 def recvUpdateLiveClient(self, user, xml):
     self.authUser(user)
     
     if type(xml) == str:
         xml = ElementTree.XML(xml)
         
     maintainIpElem = xml.find("maintainIp")
     if maintainIpElem == None:
         return False
     self.setMaintainanceIp(user, str(maintainIpElem.text))
     self.lastSeenClient = datetime.datetime.now()
     session = dissomniag.Session()
     dissomniag.saveCommit(session)
     return True
示例#35
0
def _getControlIdentity():
    session = dissomniag.Session()
    try:
        central = session.query(dissomniag.model.ControlSystem).one()
    except NoResultFound:
        central = dissomniag.model.ControlSystem()
        dissomniag.saveCommit(session)
        session.expire(central)
        return central
    except MultipleResultsFound:
        session.expire(central[0])
        return central[0]
    else:
        session.expire(central)
        return central
示例#36
0
 def run(self):
     if not hasattr(self.context, "host") or  type(self.context.host) != dissomniag.model.Host:
         self.job.trace("CheckHostUpTask: In Context missing host object.")
         raise dissomniag.taskManager.UnrevertableFailure("In Context missing host object.")
     
     if ((self.context.host.networks != None and len(self.context.host.networks) != 0) or (self.context.host.virtualMachines != None and len(self.context.host.virtualMachines) != 0)):
         self.job.trace("Host %s cannot be deleted securely: Make sure that all networks and all VM's on the Host are deleted.")
         raise dissomniag.taskManager.UnrevertableFailure("Not all VM's or Nets are deleted on Host")
     try: 
         session = dissomniag.Session()
         session.delete(self.context.host)
         dissomniag.saveCommit(session)
         self.context.host = None
     except Exception, e:
         raise dissomniag.taskManager.UnrevertableFailure("Cannot delete Host. SqlalchemyError: %s" % e)
示例#37
0
def _getControlIdentity():
    session = dissomniag.Session()
    try:
        central = session.query(dissomniag.model.ControlSystem).one()
    except NoResultFound:
         central = dissomniag.model.ControlSystem()
         dissomniag.saveCommit(session)
         session.expire(central)
         return central
    except MultipleResultsFound:
        session.expire(central[0])
        return central[0]
    else:
        session.expire(central)
        return central
示例#38
0
 def implementation(self, *args):
     sys.stdout = self.terminal
     sys.stderr = self.terminal
     
     parser = argparse.ArgumentParser(description = "Delete a key", prog = args[0])
     parser.add_argument("keyId", action = "store", type = int, help = "Enter the Key-ID of the key you want to delete.")
     if self.user.isAdmin:
         parser.add_argument("-u", "--username", action = "store", help = "The user where to delete a key.", dest = "username", default = None)
         parser.add_argument("-f", "--force", action = "store_true", help = "Force to delete key in all users.", dest = "force", default = False)
     options = parser.parse_args(args[1:])
     
     session = dissomniag.Session()
     
     user = self.user
     
     if self.user.isAdmin:
         if options.force:
             try:
                 key = session.query(PublicKey).filter(PublicKey.id == options.keyId).one()
             except Exception:
                 self.printError("Could not find Key.")
                 return
             session.delete(key)
             dissomniag.saveCommit(session)
             dissomniag.saveFlush(session)
             return
         
         if options.username and options.username != self.user.username:
             # Change in other user
             try:
                 user = session.query(User).filter(User.username == options.username).one()
             except NoResultFound:
                 self.printError("Could not find user.")
                 return
         
     for key in user.publicKeys:
         if key.id == options.keyId:
             user.publicKeys.remove(key)
             if len(key.users) == 0:
                 #Only the actual user owns that key
                 session.delete(key)
                 dissomniag.saveCommit(session)
                 dissomniag.saveFlush(session)
             return
                     
     #Key not found
     self.printError("Could not find the key. Key-ID: %s" % options.keyId)
     return
示例#39
0
 def implementation(self, *args):
     sys.stdout = self.terminal
     sys.stderr = self.terminal
     
     if not self.user.isAdmin:
         self.printError("Only Admin Users can add Hosts!")
         return
     
     parser = argparse.ArgumentParser(description = 'Add a Host to the Dissomniag System', prog = args[0])
     parser.add_argument("commonName", action = "store")
     parser.add_argument("ipAddress", action = "store")
     parser.add_argument("-u", "--adminUser", dest = "adminUser", action = "store", default = None)
     parser.add_argument("-b", "--bridgeName", dest = "bridgeName", action = "store", default = None)
     
     options = parser.parse_args(args[1:])
     
     if not dissomniag.model.IpAddress.checkValidIpAddress(options.ipAddress):
         self.printError("The IpAddress is not valid.")
         return
     
     if options.adminUser == None:
         adminUser = "******"
     else:
         adminUser = options.adminUser
 
     if options.bridgeName == None:
         bridgeName = "br0"
     else:
         bridgeName = str(options.bridgeName)
     
     session = dissomniag.Session()
     try:
         found = session.query(dissomniag.model.Host).filter(dissomniag.model.Host.commonName == options.commonName).one()
     except NoResultFound:
         pass
     except MultipleResultsFound:
         self.printError("Query Inconsistency")
         return
     else:
         if not found:
             pass
         self.printError("The hostname is already in use.")
         return
     host = dissomniag.model.Host(self.user, commonName = options.commonName, maintainanceIP = options.ipAddress, administrativeUserName = adminUser, bridgedInterfaceName = bridgeName)
     session.add(host)
     dissomniag.saveCommit(session)
     
     self.printSuccess("Host added. Make sure to add the SSH-Key %s to the admin user on the Host!" % os.path.abspath(dissomniag.config.dissomniag.rsaKeyPublic))
示例#40
0
 def __init__(self, user, network, host, topology = None, name = None):
     if host != None:
         assert isinstance(host, dissomniag.model.Host)
         if name == None:
             name = self.findEmptyName(host)
     if name != None:
         self.name = name
     else:
         self.name = "<EmptyName>"
     if topology:
         self.topology = topology
     super(generatedNetwork, self).__init__(user = user, network = network, node = host, name = name)
     self.setDhcpServerAddress(user)
     self.state = GenNetworkState.INACTIVE
     session = dissomniag.Session()
     dissomniag.saveCommit(session)
示例#41
0
 def run(self):
     if not hasattr(self.context, "topology") or  type(self.context.topology) != dissomniag.model.Topology:
         self.job.trace("DeleteTopology: In Context missing topology object.")
         raise dissomniag.taskManager.UnrevertableFailure("In Context missing topology object.")
     if ((self.context.topology.generatedNetworks != None and len(self.context.topology.generatedNetworks) != 0) or
             (self.context.topology.vms != None and len(self.context.topology.vms) != 0)):
         self.job.trace("Topology %s cannot be deleted securely: Make sure that all networks and all VM's of the Topology are deleted.")
         raise dissomniag.taskManager.UnrevertableFailure("Not all VM's or Nets are deleted in Topology")
      
     try:
         session = dissomniag.Session()
         session.delete(self.context.topology)
         dissomniag.saveCommit(session)
         self.context.topology = None
     except Exception, e: 
         raise dissomniag.taskManager.UnrevertableFailure("Cannot delete Topology. SqlalchemyError: %s" % e)
示例#42
0
 def __init__(self):
     session = dissomniag.Session()
     self.user = self.getAdministrativeUser()
     try:
         myDbObj = session.query(ControlSystem).one()
     except NoResultFound:
         myDbObj = None
     
     if myDbObj == None and dissomniag.config.dissomniag.isCentral:
         sshPrivateKey, privateKeyString, sshPublicKey, publicKeyString = self.getRsaKeys(all = True)
         sshKey = dissomniag.model.SSHNodeKey()
         sshKey.privateKey = privateKeyString
         sshKey.privateKeyFile = sshPrivateKey
         sshKey.publicKey = publicKeyString
         sshKey.publicKeyFile = sshPublicKey
         self.user.delKeys()
         self.user.addKey(sshKey.publicKey)
         super(ControlSystem, self).__init__(user = self.user, commonName = "Main",
              sshKey = sshKey,
              utilityFolder = os.path.abspath(dissomniag.config.dissomniag.configDir),
              state = dissomniag.model.NodeState.UP,
              parseLocalInterfaces = True)
         session.add(self)
         self.parseLocalInterfaces(self.user)
         
     elif myDbObj != None and dissomniag.config.dissomniag.isCentral:
         self.commonName = "Main"
         self.state = dissomniag.model.NodeState.UP
         self.utilityFolder = os.path.abspath(dissomniag.config.dissomniag.configDir)
         # Refresh Administrative User keys
         self.user.delKeys()
         self.user.addKey(myDbObj.sshKey.publicKey)
     elif not dissomniag.config.dissomniag.isCentral:
         self.commonName = "Main"
         assert dissomniag.config.dissomniag.centralIp != None
         
         if self.checkCentralSystemRunning(dissomniag.config.dissomnig.centralIP):
             self.state = dissomniag.model.NodeState.UP
         else:
             self.state = dissomniag.model.NodeState.DOWN
         
     if myDbObj == None:
         session.add(self)
     
     dissomniag.saveCommit(session)
示例#43
0
 def cleanUpJobDbViaZombi(user):
     """
     Delete all Zombi Jobs
     """
     session = dissomniag.Session()
     if not user.isAdmin:
         return False
     
     try:
         jobs = session.query(JobInfo).filter(JobInfo.user == None).all()
     except NoResultFound:
         return False
     
     for job in jobs:
         session.delete(job)
         
     dissomniag.saveCommit(session)
     return True
示例#44
0
 def cleanUpJobDb(user):
     """
     Delete Jobs in Db
     If user == adminUser all Final State jobs are deleted
     """
     session = dissomniag.Session()
     try:
         if user.isAdmin:
             jobs = session.query(JobInfo).filter(JobInfo.state.in_(JobStates.getFinalStates())).all()
         else:
             jobs = session.query(JobInfo).filter(JobInfo.state.in_(JobStates.getFinalStates())).filter(JobInfo.user == user).all()
     except NoResultFound:
         return False
     
     for job in jobs:
         session.delete(job)
     dissomniag.saveCommit(session)
     return True
示例#45
0
文件: VM.py 项目: swallat/DiSSOmniaG
 def __init__(self, user, commonName, host):
     
     sshKey = SSHNodeKey.generateVmKey(commonName, user="******")
     
     super(VM, self).__init__(user, commonName, sshKey = sshKey, state = dissomniag.model.NodeState.NOT_CREATED)
     if host != None and isinstance(host, dissomniag.model.Host):
         self.setHost(user, host)
     self.selectInitialStateActor()
     self.vncPassword = dissomniag.utils.random_password()
     
     interface = self.addInterface(user, "maintain")
     interface.maintainanceInterface = True
         
     self.liveCd = dissomniag.model.LiveCd(self)
     self.maintainUser = dissomniag.auth.User(username = self.commonName, password = self.uuid, isAdmin = False, loginRPC = True, loginSSH = False, loginManhole = False, maintain= True)
     
     session = dissomniag.Session()    
     dissomniag.saveCommit(session)
示例#46
0
    def __init__(self, user, network, node=None, name=None):

        session = dissomniag.Session()
        if type(network) == str:
            network = ipaddr.IPNetwork(network)

        if name == None:
            name = "PublicNetwork"
        self.uuid = str(uuid.uuid4())
        self.name = name

        self.netAddress = str(network.network)
        self.netMask = str(network.netmask)
        session.add(self)

        if node != None:
            self.addNode(user, node)
        dissomniag.saveCommit(session)
示例#47
0
 def run(self):
     if not hasattr(self.context, "net") or not isinstance(self.context.net, dissomniag.model.Network):
         self.job.trace("DeleteIpAddressesOnNetwork: In Context missing net object.")
         raise dissomniag.taskManager.UnrevertableFailure("In Context missing net object.")
     
     if isinstance(self.context.net, dissomniag.model.generatedNetwork):
         if self.context.net.state == dissomniag.model.GenNetworkState.CREATED:
             self.job.trace("DeleteNetwork: Network is still running")
             raise dissomniag.taskManager.UnrevertableFailure()
     
     try:
         session = dissomniag.Session()
         session.delete(self.context.net)
         dissomniag.saveCommit(session)
         self.context.net = None
     except Exception, e:
         self.job.trace("Cannot delete Network. Sqlalchemy Error: %s" % e)
         raise dissomniag.taskManager.UnrevertableFailure("Cannot delete Network. Sqlalchemy Error %s" % e)
示例#48
0
文件: VM.py 项目: swallat/DiSSOmniaG
    def deleteVm(user, node):
        if node == None or not isinstance(node, VM):
            return False
        node.authUser(user)
        
        #1. Delete LiveCD
        if node.liveCd != None and type(node.liveCd) == dissomniag.model.LiveCd:
            dissomniag.model.LiveCd.deleteLiveCd(user, node.liveCd)
        
        #2. Delete maintainance User
        if node.maintainUser != None and type(node.maintainUser) == dissomniag.auth.User and node.maintainUser.isMaintain:
            session = dissomniag.Session()
            session.delete(node.maintainUser)
            dissomniag.saveCommit(session)

        #2. Delete Interfaces
        for interface in node.interfaces:
            dissomniag.model.Interface.deleteInterface(user, interface)
        
        
        context = dissomniag.taskManager.Context()
        context.add(node, "vm")
        context.add(node, "node")
        job = dissomniag.taskManager.Job(context, description = "Delete a VM", user = user)
        #3. Delete IPAddresses
        job.addTask(dissomniag.tasks.DeleteIpAddressesOnNode())
        
        #4. Delete VM
        job.addTask(dissomniag.tasks.DeleteVM())
        
        #5. Delete all Topology Connection for this VM
        session = dissomniag.Session()
        
        try:
            connections = session.query(dissomniag.model.TopologyConnection).filter(sa.or_(dissomniag.model.TopologyConnection.fromVM == node, dissomniag.model.TopologyConnection.toVM == node)).all()
        except NoResultFound:
            pass
        else:
            for connection in connections:
                session.delete(connection)
            dissomniag.saveCommit(session)
        
        dissomniag.taskManager.Dispatcher.addJobSyncronized(user = user, syncObj = dissomniag.GitEnvironment(), job = job)
        return True