Example #1
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
Example #2
0
    def printVm(self, vm, withXml=False):
        session = dissomniag.Session()
        session.expire(vm)
        print("VM Name: %s" % str(vm.commonName))
        print("UUID: %s" % str(vm.uuid))
        print("State: %s" %
              str(dissomniag.model.NodeState.getStateName(vm.state)))
        print("RamSize: %s" % str(vm.ramSize))
        #print("HD Created?: %s" % str(vm.isHdCreated))
        #print("Use HD: %s" % str(vm.useHD))
        #print("HdSize: %s" % str(vm.hdSize))
        print("VNC Port: %s" % str(vm.vncPort))
        print("VNC Password: %s" % str(vm.vncPassword))
        print("InstalledSoftware: %s" % str(vm.dynamicAptList))
        if vm.lastSeenClient == None:
            self.printError("Live Client last seen: %s" %
                            str(vm.lastSeenClient))
        else:
            self.printSuccess("Live Client last seen: %s" %
                              str(vm.lastSeenClient))
        for interface in vm.interfaces:
            print("InterfaceName: %s Mac: %s" %
                  (str(interface.name), str(interface.macAddress)))
            if interface.ipAddresses != []:
                print("\t Address: %s" % str(interface.ipAddresses[0].addr))

        if withXml:
            print("XML: \n %s" % vm.getLibVirtString(self.user))
        print("\n")
Example #3
0
    def parse(self, user):
        self.user = user
        session = dissomniag.Session()
        allObjects = dir(self)
        for obj in allObjects:
            if obj.startswith("_"):
                continue
            attribute = getattr(self, obj)
            if not type(attribute) == dict:
                continue
            if "class" not in attribute or "id" not in attribute:
                continue
            found = False
            try:
                newObj = session.query(attribute['class']).filter(
                    attribute['class'].id == attribute['id']).one()
                found = True
            except NoResultFound:
                found = False
            except MultipleResultsFound:
                allObj = session.query(attribute['class']).filter(
                    attribute['class'].id == attribute['id']).all()
                newObj = allObj[0]
                found = True

            if found == True:
                setattr(self, obj, newObj)
Example #4
0
 def implementation(self, *args):
     sys.stdout = self.terminal
     sys.stderr = self.terminal
     
     parser = argparse.ArgumentParser(description = 'List Apps', prog = args[0])
     
     parser.add_argument("-a", "--all", dest = "all", action = "store_true", default = False)
     parser.add_argument("-l", "--log", dest = "log", action = "store_true", default = False)
     parser.add_argument("-n" , "--name", dest = "name", action = "store", default = None)
     
     options = parser.parse_args(args[1:])
     
     withLog = options.log
     all = options.all
     name = options.name
     
     session = dissomniag.Session()
     
     if name != None:
         try:
             app = session.query(dissomniag.model.App).filter(dissomniag.model.App.name == name).one()
         except NoResultFound:
             self.printError("No App Found with this name!")
             return
         except MultipleResultsFound:
             apps = session.query(dissomniag.model.App).filter(dissomniag.model.App.name == name).all()
             foundOne = False
             for app in apps:
                 if self.user in app.users or self.user.isAdmin:
                     foundOne = True
                     self.printApp(app, withLog)
             if not foundOne:
                 self.printError("There are no Apps with name %s for user %s." %(name, self.user.username))
             return
         else:
             if self.user in app.users or self.user.isAdmin:
                 self.printApp(app, withLog)
             else:
                 self.printError("There are no Apps with name %s for user %s." %(name, self.user.username))
             return
     
     if self.user.isAdmin and all:
         try:
             apps = session.query(dissomniag.model.App).all()
         except NoResultFound:
             return
         else:
             for app in apps:
                 self.printApp(app, withLog)
     
     try:
         apps = session.query(dissomniag.model.App).all()
     except NoResultFound:
         return
     else:
         for app in apps:
             if self.user in app.users:
                 self.printApp(app, withLog)
     
     return
Example #5
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='List All Hosts',
                                         prog=args[0])
        parser.add_argument("-c",
                            "--withCapabilities",
                            dest="withCap",
                            action="store_true",
                            default=False)

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

        session = dissomniag.Session()
        hosts = None
        try:
            hosts = session.query(dissomniag.model.Host).all()
        except NoResultFound:
            pass

        for host in hosts:
            self.printHost(host, withCap=options.withCap)
Example #6
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)
Example #7
0
 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)
Example #8
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
Example #9
0
    def run(self):
        if not hasattr(self.context, "host") or type(
                self.context.host) != dissomniag.model.Host:
            self.job.trace(
                "chekLibvirtVersionOnHost: In Context missing host object.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "In Context missing host object.")

        maintainanceIp = self.context.host.getMaintainanceIP().addr
        self.job.trace(
            "checkLibvirtVersionOnHost: (Host: %s) virsh --version" %
            self.context.host.commonName)

        sshCmd = dissomniag.utils.SSHCommand(
            "virsh --version",
            hostOrIp=maintainanceIp,
            username=self.context.host.administrativeUserName)
        code, output = sshCmd.callAndGetOutput(withError=False)
        if code != 0:
            self.job.trace(
                "checkLibvirtVersionOnHost: Could not execute 'virsh --version'!"
            )
            return dissomniag.taskManager.TaskReturns.FAILED_BUT_GO_AHEAD
        self.context.host.changeState(self.job.getUser(),
                                      dissomniag.model.NodeState.UP)
        self.context.host.libvirtVersion = output[0]
        self.context.host.lastChecked = datetime.datetime.now()
        session = dissomniag.Session()
        dissomniag.saveFlush(session)
        return dissomniag.taskManager.TaskReturns.SUCCESS
Example #10
0
    def test(self, job):
        session = dissomniag.Session()
        try:
            con = libvirt.open(str(self.vm.host.qemuConnector))
        except libvirt.libvirtError:
            self.vm.lastSeenCient = None
            dissomniag.saveCommit(session)
            self.vm.changeState(dissomniag.model.NodeState.RUNTIME_ERROR)
            raise dissomniag.taskManager.TaskFailed(
                "Could Not Connect to Libvirt Host!")

        try:
            vm = con.lookupByName(self.vm.commonName)
        except libvirt.libvirtError:
            job.trace("VM is not Running.")
            self.vm.lastSeenCient = None
            dissomniag.saveCommit(session)
            self.vm.changeState(dissomniag.model.NodeState.RUNTIME_ERROR)
            return self.vm.runningState.sanityCheck(job)

        if vm.isActive() == 1:
            job.trace("VM state is correct!")
            return True
        else:
            try:
                vm.destroy()
            except libvirt.libvirtError as e:
                pass
            job.trace("VM is not Running.")
            self.vm.lastSeenCient = None
            dissomniag.saveCommit(session)
            self.vm.changestate(dissomniag.model.NodeState.RUNTIME_ERROR)
            return self.vm.runningState.sanityCheck(job)
Example #11
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
Example #12
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
Example #13
0
 def parseLocalInterfaces(self, user):
     
     self.authUser(user)
     
     excludedInterfaces = ['lo', 'lo0']
     excludedIps = ['fe80:', '172.0.0.1']
     interfaceCodes = {"mac" : 17, 'ipv4': 2 , 'ipv6' : 10}
     session = dissomniag.Session()
     interfaces = netifaces.interfaces()
     
     savedInterfaces = []
     
     for interface in interfaces:
         if interface in excludedInterfaces:
             continue
         myInt = None
         
         addresses = netifaces.ifaddresses(interface)
         for key in addresses:
             if key == interfaceCodes['mac'] and myInt == None:
                 for address in addresses[key]:
                     try:
                         myInt = session.query(Interface).filter(Interface.macAddress == address['addr']).one()
                         continue # Check if IP have changed
                     except NoResultFound:
                         myInt = Interface(user, self, interface, address['addr'])
             elif (key == interfaceCodes['ipv4'] or key == interfaceCodes['ipv6']) and myInt != None:
                 
                 for address in addresses[key]:
                     found = False
                     for exclude in excludedIps:
                         if address['addr'].startswith(exclude):
                             found = True
                             break
                     if found:
                         continue
                     if key == interfaceCodes['ipv4']:
                         ipFullString = ("%s/%s" % (address['addr'], address['netmask']))
                     else:
                         try:
                             ipv6Netmask = dissomniag.model.IpAddress.parseIpv6Netmask(address['netmask'])
                         except dissomniag.model.NoIpv6Mask:
                             continue
                         else:
                             ipFullString = ("%s/%s" % (address['addr'], ipv6Netmask))
                     
                     
                     myInt.addIp(user, ipFullString)
                 
             else:
                 print("parseLocalInterfaces tried to add a seond mac to a interface or tried to add a ip to a non existing interface")
         if myInt != None:
             self.interfaces.append(myInt)
             savedInterfaces.append(myInt)
     # Delete unused Interfaces
     for interface in self.interfaces:
         if not (interface in savedInterfaces):
             Interface.deleteInterface(user, interface, isAdministrative = True)
     if self.getMaintainanceIP() == None:
         self._selectInitialMaintainanceInterface(user)
Example #14
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]
Example #15
0
 def __init__(self, app, liveCd):
     self.app = app
     self.liveCd = liveCd
     
     session = dissomniag.Session()
     session.add(self)
     dissomniag.saveCommit(session)
Example #16
0
    def run(self):
        if not hasattr(self.context, "host") or type(
                self.context.host) != dissomniag.model.Host:
            self.job.trace("chekKvmOnHost: In Context missing host object.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "In Context missing host object.")

        maintainanceIp = self.context.host.getMaintainanceIP().addr
        self.job.trace(
            "chekKvmOnHost: (Host: %s) egrep vmx --color=always /proc/cpuinfo"
            % self.context.host.commonName)
        sshCmd1 = dissomniag.utils.SSHCommand(
            "egrep vmx --color=always /proc/cpuinfo",
            hostOrIp=maintainanceIp,
            username=self.context.host.administrativeUserName)
        code1, output1 = sshCmd1.callAndGetOutput()
        sshCmd2 = dissomniag.utils.SSHCommand(
            "egrep svm --color=always /proc/cpuinfo",
            hostOrIp=maintainanceIp,
            username=self.context.host.administrativeUserName)
        code2, output2 = sshCmd2.callAndGetOutput()
        if code1 != 0 and code2 != 0:
            out = "\n".join(output1 + output2)
            self.job.trace(
                "checkLibvirtVersionOnHost: Could not execute 'egrep vmx --color=always /proc/cpuinfo' %s!"
                % out)
            self.context.host.kvmUsable = False
            return dissomniag.taskManager.TaskReturns.FAILED_BUT_GO_AHEAD
        self.context.host.changeState(self.job.getUser(),
                                      dissomniag.model.NodeState.UP)
        self.context.host.kvmUsable = True
        self.context.host.lastChecked = datetime.datetime.now()
        session = dissomniag.Session()
        dissomniag.saveFlush(session)
        return dissomniag.taskManager.TaskReturns.SUCCESS
Example #17
0
 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
Example #18
0
    def run(self):
        if not hasattr(self.context, "host") or type(
                self.context.host) != dissomniag.model.Host:
            self.job.trace(
                "getRamCapacityOnHost: In Context missing host object.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "In Context missing host object.")

        maintainanceIp = self.context.host.getMaintainanceIP().addr
        self.job.trace(
            "getRamCapacityOnHost: (Host: %s) at /proc/meminfo | head -n 1 | awk '/[0-9]/ {print $2}'"
            % self.context.host.commonName)
        sshCmd = dissomniag.utils.SSHCommand(
            "cat /proc/meminfo",
            hostOrIp=maintainanceIp,
            username=self.context.host.administrativeUserName)
        code, output = sshCmd.callAndGetOutput()
        if code != 0:
            self.job.trace("getRamCapacityOnHost: Unable to get RAM Capacity.")
            return dissomniag.taskManager.TaskReturns.FAILED_BUT_GO_AHEAD
        line = shlex.split(
            output[0])  #The first line is the only interesting line
        self.context.host.ramCapacity = str(
            int(line[1]) /
            1024) + "MB"  # The second fieled in this line is interesting
        self.context.host.lastChecked = datetime.datetime.now()
        self.context.host.changeState(self.job.getUser(),
                                      dissomniag.model.NodeState.UP)
        session = dissomniag.Session()
        dissomniag.saveFlush(session)
        return dissomniag.taskManager.TaskReturns.SUCCESS
Example #19
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)
Example #20
0
    def run(self):
        if not hasattr(self.context, "vm") or not isinstance(
                self.context.vm, dissomniag.model.VM):
            self.job.trace("resetVM: In Context missing net object.")
            raise dissomniag.taskManager.UnrevertableFailure(
                "In Context missing net object.")

        cycleCounter = 0
        session = dissomniag.Session()
        session.expire(self.context.vm)
        while (
            (self.context.vm.state != dissomniag.model.NodeState.NOT_CREATED)
                and (cycleCounter <= 4)):
            try:
                self.context.vm.reset(self.job.getUser(), self.job)
            except Exception as e:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                traceback.print_tb(exc_traceback)
                self.job.trace(str(e))
                pass

            cycleCounter = cycleCounter + 1
            session.expire(self.context.vm)

        if self.context.vm.state == dissomniag.model.NodeState.NOT_CREATED:
            return dissomniag.taskManager.TaskReturns.SUCCESS
        else:
            raise dissomniag.taskManager.UnrevertableFailure(
                "Could not reset VM!")
Example #21
0
 def implementation(self, *args):
     sys.stdout = self.terminal
     sys.stderr = self.terminal
     
     parser = argparse.ArgumentParser(description = 'Delete a App', prog = args[0])
     
     parser.add_argument("appName", action = "store")
     
     options = parser.parse_args(args[1:])
     
     session = dissomniag.Session()
     
     name = str(options.appName)
     
     try:
         apps = session.query(dissomniag.model.App).filter(dissomniag.model.App.name == name).all()
     except NoResultFound:
         self.printError("There is no app with name %s." % name)
         return
     else:
         found = False
         for app in apps:
             if app.name == name and ((self.user in app.users) or (self.user.isAdmin)):
                 found = True
                 try:
                     dissomniag.model.App.delApp(self.user, app)
                 except Exception as e:
                     self.printError("Delete error. %s" % str(e))
         if not found:
             self.printError("There is no app with name %s." % name)
         else:
             self.printSuccess("Successfully deleted app %s." % name)
         
         return
Example #22
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)
Example #23
0
    def implementation(self, *args):
        sys.stdout = self.terminal
        sys.stderr = self.terminal

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

        parser = argparse.ArgumentParser(description="Delete a Host",
                                         prog=args[0])
        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 not dissomniag.model.Host.deleteHost(self.user, host):
            self.printError("Could not delete Host.")
Example #24
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)
Example #25
0
    def printHost(self, host, withCap=False):

        if host == None or type(host) != dissomniag.model.Host:
            print(str(type(host)))
            print(str(dissomniag.model.Host == type(host)))
            return
        session = dissomniag.Session()
        session.expire(host)

        print("Common Name: %s" % str(host.commonName))
        print("State: %s" %
              str(dissomniag.model.NodeState.getStateName(host.state)))
        print("UUID: %s" % str(host.uuid))
        print("MaintainanceIP: %s" % str(host.getMaintainanceIP().addr))
        print("AdministrativeUserName: %s" % str(host.administrativeUserName))
        print("BridgedInterfaceName: %s" % str(host.bridgedInterfaceName))
        print("lastChecked: %s" % str(host.lastChecked))
        print("Libvirt Version: %s" % str(host.libvirtVersion))
        print("KVMUsable: %s" % str(host.kvmUsable))
        print("FreeDiskspace: %s" % str(host.freeDiskspace))
        print("RamCapacity: %s" % str(host.ramCapacity))
        print("ConfigurarionMissmatch: %s" % str(host.configurationMissmatch))
        if withCap:
            print("LibVirtCapabilities: \n %s" % str(host.libvirtCapabilities))
        print("\n")
Example #26
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
Example #27
0
    def implementation(self, *args):
        sys.stdout = self.terminal
        sys.stderr = self.terminal

        if not self.user.isAdmin:
            self.printError("Only Admin Users can reset a VM!")
            return

        parser = argparse.ArgumentParser(description='Total reset a VM',
                                         prog=args[0])

        parser.add_argument("vmName", action="store")

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

        vmName = str(options.vmName)

        session = dissomniag.Session()

        try:
            vm = session.query(dissomniag.model.VM).filter(
                dissomniag.model.VM.commonName == vmName).one()
        except NoResultFound:
            self.printError("There is no Vm with the name: %s" % vmName)
            return
        except MultipleResultsFound:
            self.printError("Query Inconsistency.")
            return

        vm.createTotalResetJob(self.user)
Example #28
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)
Example #29
0
    def implementation(self, *args):
        sys.stdout = self.terminal
        sys.stderr = self.terminal

        parser = argparse.ArgumentParser(description='Print out all users.',
                                         prog=args[0])

        parser.add_argument("-k",
                            action="store_true",
                            dest="printKeys",
                            default=False)
        options = parser.parse_args(list(args[1:]))
        session = dissomniag.Session()

        for user in session.query(User).all():
            session.expire(user)
            if (not self.user.isAdmin and user.username != self.user.username
                ) or user.username == dissomniag.Identity.systemUserName:
                continue
            self.printSuccess(str("User: %s" % user.username))
            print(str("\t isAdmin: %s" % user.isAdmin))
            if self.user.isAdmin:
                print(str("\t loginRPC: %s" % user.loginRPC))
                print(str("\t loginSSH: %s" % user.loginSSH))
                print(str("\t loginManhole: %s" % user.loginManhole))
            if options.printKeys and user.publicKeys:
                print(
                    self.colorString(str("\t Public Keys: "),
                                     style=Style.BRIGHT))
                for key in user.publicKeys:
                    self.printInfo("Key-ID: %i" % key.id)
                    self.printInfo(str("%s" % key.publicKey))
            print("\n")
Example #30
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