Beispiel #1
0
    def __init__(self, model_controller, plugin_controller):
        self.active_workspace = None

        self._couchAvailable = False
        self.report_manager = ReportManager(10, plugin_controller)

        self.couchdbmanager = PersistenceManagerFactory().getInstance()
        self.fsmanager = FSManager()

        self._workspaces = {}
        self._workspaces_types = {}
        self._model_controller = model_controller
        self._excluded_directories = [".svn"]
        self.workspace_persister = WorkspacePersister()
Beispiel #2
0
    def _showRepositoryConfigDialog(self):

        repoconfig_dialog = RepositoryConfigDialog(self,
                                                   CONF.getCouchURI(),
                                                   CONF.getCouchIsReplicated(),
                                                   CONF.getCouchReplics(),
                                                   callback=None)
        result = repoconfig_dialog.exec_loop()
        if result == qt.QDialog.Accepted:
            repourl, isReplicated, replics = repoconfig_dialog.getData()
            api.devlog("repourl = %s" % repourl)
            wm = self._main_app.getWorkspaceManager()
            if not CouchdbManager.testCouch(repourl):
                self.showPopup("""
                Repository URL Not valid, check if
                service is available and that connection string is from
                the form: http[s]://hostname:port""")
                repourl, isReplicated, replics = "", False, ""

            CONF.setCouchUri(repourl)
            CONF.setCouchIsReplicated(isReplicated)
            CONF.setCouchReplics(replics)
            CONF.saveConfig()

            couchdbmanager = PersistenceManagerFactory().getInstance()
            wm.setCouchManager(couchdbmanager)

            wm.loadWorkspaces()
            mwin = self._main_app.getMainWindow()
            mwin.getWorkspaceTreeView().loadAllWorkspaces()
            mwin.getWorkspaceTreeView().setDefaultWorkspace()
Beispiel #3
0
 def __init__(self, model_controller, plugin_controller):
     self.active_workspace = None
                                                               
     self._couchAvailable  = False 
     self.report_manager = ReportManager(10, plugin_controller)
     
     self.couchdbmanager = PersistenceManagerFactory().getInstance()
     
     self._workspaces = {}
     self._model_controller = model_controller
     self._excluded_directories = [".svn"]
     self.workspace_persister = WorkspacePersister()
Beispiel #4
0
    def test_save_command_in_couch(self):
        """ Tests if command is saved in couch """
        cm = CommandManager()

        exec_command = CommandRunInformation(**self.getDefaultCommandInfo())

        wm = WorkspaceManager(mock(ModelController), mock(PluginController))
        workspace = wm.createWorkspace(exec_command.workspace, workspaceClass=WorkspaceOnCouch)

        res = cm.saveCommand(exec_command, workspace)

        self._manager = PersistenceManagerFactory.getInstance()
        saved_doc = self._manager.getDocument(exec_command.workspace, res['id'] )

        self.assertEquals(exec_command.command, saved_doc['command'], 'Saved command diffier')
        self.assertEquals(exec_command.parameters, saved_doc['parameters'], 'Saved command diffier')
        self.assertEquals(exec_command.itime, saved_doc['itime'], 'Saved command diffier')
        self.assertEquals(exec_command.duration, saved_doc['duration'], 'Saved command diffier')
Beispiel #5
0
    def test_save_command_in_fs(self):
        """ Tests if command is saved in couch """
        wm = WorkspaceManager(mock(ModelController), mock(PluginController))

        command_info = self.getDefaultCommandInfo()
        command_info['workspace'] = 'new_workspace'
        exec_command = CommandRunInformation(**command_info)

        workspace = wm.createWorkspace(exec_command.workspace, workspaceClass=WorkspaceOnFS)
        wm.setActiveWorkspace(workspace)

        cm = CommandManager()

        res = cm.saveCommand(exec_command, workspace)

        self._manager = PersistenceManagerFactory.getInstance()
        # saved_doc = self._manager.getDocument(exec_command.workspace, res['id'])

        # After all
        wm.removeWorkspace(command_info['workspace'])
Beispiel #6
0
    def test_save_command_in_fs(self):
        """ Tests if command is saved in couch """
        wm = WorkspaceManager(mock(ModelController), mock(PluginController))

        command_info = self.getDefaultCommandInfo()
        command_info['workspace'] = 'new_workspace'
        exec_command = CommandRunInformation(**command_info)

        workspace = wm.createWorkspace(exec_command.workspace,
                                       workspaceClass=WorkspaceOnFS)
        wm.setActiveWorkspace(workspace)

        cm = CommandManager()

        res = cm.saveCommand(exec_command, workspace)

        self._manager = PersistenceManagerFactory.getInstance()
        # saved_doc = self._manager.getDocument(exec_command.workspace, res['id'])

        # After all
        wm.removeWorkspace(command_info['workspace'])
Beispiel #7
0
    def test_save_command_in_couch(self):
        """ Tests if command is saved in couch """
        cm = CommandManager()

        exec_command = CommandRunInformation(**self.getDefaultCommandInfo())

        wm = WorkspaceManager(mock(ModelController), mock(PluginController))
        workspace = wm.createWorkspace(exec_command.workspace,
                                       workspaceClass=WorkspaceOnCouch)

        res = cm.saveCommand(exec_command, workspace)

        self._manager = PersistenceManagerFactory.getInstance()
        saved_doc = self._manager.getDocument(exec_command.workspace,
                                              res['id'])

        self.assertEquals(exec_command.command, saved_doc['command'],
                          'Saved command diffier')
        self.assertEquals(exec_command.parameters, saved_doc['parameters'],
                          'Saved command diffier')
        self.assertEquals(exec_command.itime, saved_doc['itime'],
                          'Saved command diffier')
        self.assertEquals(exec_command.duration, saved_doc['duration'],
                          'Saved command diffier')
Beispiel #8
0
class WorkspaceManager(object):
    """
    This handles all workspaces. It checks for existing workspaces inside
    the persistence directory.
    It is in charge of starting the WorkspacesAutoSaver to persist each workspace.
    This class stores information in $HOME/.faraday/config/workspacemanager.xml file
    to keep track of created workspaces to be able to load them
    """
    def __init__(self, model_controller, plugin_controller):
        self.active_workspace = None

        self._couchAvailable = False
        self.report_manager = ReportManager(10, plugin_controller)

        self.couchdbmanager = PersistenceManagerFactory().getInstance()
        self.fsmanager = FSManager()

        self._workspaces = {}
        self._workspaces_types = {}
        self._model_controller = model_controller
        self._excluded_directories = [".svn"]
        self.workspace_persister = WorkspacePersister()

    def couchAvailable(self, isit):
        self._couchAvailable = isit

    def _notifyWorkspaceNoConnection(self):
        notifier.showPopup(
            "Couchdb Connection lost. Defaulting to memory. Fix network and try again in 5 minutes."
        )

    def reconnect(self):
        if not self.reconnectCouchManager():
            self._notifyWorkspaceNoConnection()

    def getCouchManager(self):
        return self.couchdbmanager

    def setCouchManager(self, cm):
        self.couchdbmanager = cm

    @staticmethod
    def getAvailableWorkspaceTypes():
        av = [
            w.__name__ for w in Workspace.__subclasses__() if w.isAvailable()
        ]
        model.api.devlog("Available wortkspaces: %s" ", ".join(av))
        return av

    def reconnectCouchManager(self):
        retval = True
        if not self.couchdbmanager.reconnect():
            retval = False
            return retval
        WorkspacePersister.reExecutePendingActions()
        return retval

    def startAutoLoader(self):
        pass

    def stopAutoLoader(self):
        pass

    def startReportManager(self):
        self.report_manager.start()

    def stopReportManager(self):
        self.report_manager.stop()
        self.report_manager.join()

    def getActiveWorkspace(self):
        return self.active_workspace

    def saveWorkspaces(self):
        pass

    def addWorkspace(self, workspace):
        self._workspaces[workspace.name] = workspace

    def createVisualizations(self):
        stat = False
        url = ""
        if self.couchdbmanager.isAvailable():
            stat = True
            url = self.couchdbmanager.pushReports()
        else:
            self._notifyNoVisualizationAvailable()
        return stat, url

    def _notifyNoVisualizationAvailable(self):
        notifier.showPopup(
            "No visualizations available, please install and configure CouchDB"
        )

    def createWorkspace(self,
                        name,
                        description="",
                        workspaceClass=None,
                        shared=CONF.getAutoShareWorkspace(),
                        customer="",
                        sdate=None,
                        fdate=None):

        model.api.devlog("Creating Workspace")
        if self.getWorkspaceType(name) in globals():
            workspaceClass = globals()[self.getWorkspaceType(name)]
        elif not workspaceClass:
            # Defaulting =(
            model.api.devlog("Defaulting to WorkspaceOnFS")
            workspaceClass = WorkspaceOnFS

        w = workspaceClass(name, self, shared)
        # Register the created workspace type:
        self._workspaces_types[name] = workspaceClass.__name__
        w.description = description
        w.customer = customer
        if sdate is not None:
            w.start_date = sdate
        if fdate is not None:
            w.finish_date = fdate
        self.addWorkspace(w)
        return w

    def removeWorkspace(self, name):
        work = self.getWorkspace(name)
        if not work: return
        dm = work.getDataManager()
        dm.removeWorkspace(name)

        datapath = CONF.getDataPath()
        todelete = [i for i in os.listdir(datapath) if name in i]
        for i in todelete:
            os.remove(os.path.join(datapath, i))

        shutil.rmtree(self.getWorkspace(name).getReportPath())
        del self._workspaces[name]
        if self.getWorkspace(name) == self.getActiveWorkspace(
        ) and self.getWorkspacesCount() > 0:
            self.setActiveWorkspace(
                self.getWorkspace(self._workspaces.keys()[0]))

    def getWorkspace(self, name):
        ''' May return None '''
        if not self._workspaces.get(name):
            # Retrieve the workspace
            self.loadWorkspace(name)
        return self._workspaces.get(name)

    def loadWorkspace(self, name):
        workspaceClass = None
        workspace = None
        if name in self.fsmanager.getWorkspacesNames():
            workspace = self.createWorkspace(name,
                                             workspaceClass=WorkspaceOnFS)
        elif name in self.couchdbmanager.getWorkspacesNames():
            workspace = self.createWorkspace(name,
                                             workspaceClass=WorkspaceOnCouch)

        return workspace

    def openWorkspace(self, name):
        w = self.getWorkspace(name)
        self.setActiveWorkspace(w)
        return w

    def getWorkspaces(self):
        """
        Simply returns a list of all existing workspaces (including the active one)
        """
        self.loadWorkspaces()
        return [w for w in self._workspaces.itervalues()]

    def getWorkspacesCount(self):
        return len(self._workspaces)

    def getWorkspacesNames(self):
        return self._workspaces.keys()

    def loadWorkspaces(self):

        self._workspaces_types = {}
        fsworkspaces = {
            name: None
            for name in self.fsmanager.getWorkspacesNames()
        }
        self._workspaces.update(fsworkspaces)
        couchworkspaces = {
            name: None
            for name in self.couchdbmanager.getWorkspacesNames()
            if not name == 'reports'
        }
        self._workspaces.update(couchworkspaces)

        self._workspaces_types.update(
            {name: WorkspaceOnFS.__name__
             for name in fsworkspaces})
        self._workspaces_types.update(
            {name: WorkspaceOnCouch.__name__
             for name in couchworkspaces})

    def getWorkspaceType(self, name):
        return self._workspaces_types.get(name, 'undefined')

    def setActiveWorkspace(self, workspace):
        try:
            self.stopAutoLoader()
        except:
            pass

        if self.active_workspace is not None:
            self.active_workspace.setModelController(None)
        CONF.setLastWorkspace(workspace.name)
        CONF.saveConfig()
        self.active_workspace = workspace
        self.active_workspace.setModelController(self._model_controller)
        self._model_controller.setWorkspace(self.active_workspace)
        self.workspace_persister.setPersister(self.active_workspace,
                                              self.active_workspace._dmanager)

        self.report_manager.path = workspace.report_path

        if isinstance(self.active_workspace, WorkspaceOnCouch):
            self.startAutoLoader()

    def isActive(self, name):
        return self.active_workspace.name == name

    def syncWorkspaces(self):
        """
        Synchronize persistence directory using the DataManager.
        We first make sure that all shared workspaces were added to the repo
        """
        pass
Beispiel #9
0
class WorkspaceManager(object):
    """
    This handles all workspaces. It checks for existing workspaces inside
    the persistence directory.
    It is in charge of starting the WorkspacesAutoSaver to persist each workspace.
    This class stores information in $HOME/.faraday/config/workspacemanager.xml file
    to keep track of created workspaces to be able to load them
    """
    def __init__(self, model_controller, plugin_controller):
        self.active_workspace = None
                                                                  
        self._couchAvailable  = False 
        self.report_manager = ReportManager(10, plugin_controller)
        
        self.couchdbmanager = PersistenceManagerFactory().getInstance()
        
        self._workspaces = {}
        self._model_controller = model_controller
        self._excluded_directories = [".svn"]
        self.workspace_persister = WorkspacePersister()

    def couchAvailable(self, isit):
        self._couchAvailable = isit

    def reconnect(self):
        if not self.reconnectCouchManager():
            self._model_controller._notifyWorkspaceConnectionLost()

    def getCouchManager(self):
        return self.couchdbmanager

    def setCouchManager(self, cm):
        self.couchdbmanager = cm

    @staticmethod
    def getAvailableWorkspaceTypes(): 
        av = [w.__name__ for w in Workspace.__subclasses__() if w.isAvailable() ]
        model.api.devlog("Available wortkspaces: %s" ", ".join(av))
        return av
        
    def reconnectCouchManager(self):
        retval = True
        if not self.couchdbmanager.reconnect():
            retval = False
            return retval
        WorkspacePersister.reExecutePendingActions() 
        return retval
    
    def startAutoLoader(self): 
        pass

    def stopAutoLoader(self):
        pass
    

    def startReportManager(self):
        self.report_manager.start()
    
    def stopReportManager(self):
        self.report_manager.stop()
        self.report_manager.join()
        
    def getActiveWorkspace(self):
        return self.active_workspace
    
    def saveWorkspaces(self):
        pass
            
    def addWorkspace(self, workspace):
        self._workspaces[workspace.name] = workspace
 
    def createVisualizations(self):
        stat = False
        url = ""
        if self.couchdbmanager.isAvailable():
            stat = True
            url  = self.couchdbmanager.pushReports() 
        else:
            self._notifyNoVisualizationAvailable() 
        return stat, url

    def _notifyNoVisualizationAvailable(self):
        guiapi.postCustomEvent((ShowPopupCustomEvent("No visualizations available, please install and configure CouchDB")))
    
    def createWorkspace(self, name, description="", workspaceClass = WorkspaceOnFS, shared=CONF.getAutoShareWorkspace(),
                        customer="", sdate=None, fdate=None):
        if name not in self._workspaces:
            w = workspaceClass(name, self, shared)
            w.description = description
            w.customer = customer
            if sdate is not None:
                w.start_date = sdate
            if fdate is not None:
                w.finish_date = fdate
            self.addWorkspace(w)
        else:
            w = self._workspaces[name]
        return w

    def removeWorkspace(self, name):
        dm = self.getWorkspace(name).getDataManager()
        dm.removeWorkspace(name)
                       
        datapath = CONF.getDataPath()
        todelete = [i for i in os.listdir(datapath) if name in i ]
        for i in todelete:
            os.remove(os.path.join(datapath, i))

        shutil.rmtree(self.getWorkspace(name).getReportPath())
        del self._workspaces[name]
        if self.getWorkspace(name) == self.getActiveWorkspace() and self.getWorkspacesCount() > 0: 
            self.setActiveWorkspace(self.getWorkspace(self._workspaces.keys()[0]))

    def getWorkspace(self, name):
        return self._workspaces.get(name)
    
    def openWorkspace(self, name):
        if name in self._workspaces:
            w = self._workspaces[name]
            self.setActiveWorkspace(w)
            return w
        raise Exception("Error on OpenWorkspace for %s "  % name)
        
    def getWorkspaces(self):
        """
        Simply returns a list of all existing workspaces (including the active one)
        """
        self.loadWorkspaces()
        return [w for w in self._workspaces.itervalues()]
    
    def getWorkspacesCount(self):
        return len(self._workspaces)

    def getWorkspacesNames(self):
        return self._workspaces.keys()
        
    def loadWorkspaces(self): 
        self._workspaces.clear()
        for name in os.listdir(CONF.getPersistencePath()):
            if name not in self._workspaces:
                if os.path.isdir(os.path.join(CONF.getPersistencePath(),name)) and name not in self._excluded_directories:
                    w = self.createWorkspace(name, workspaceClass = WorkspaceOnFS)

        for name in self.couchdbmanager.getWorkspacesNames():
            if name not in self._workspaces and not name == "reports":
                self.createWorkspace(name, workspaceClass = WorkspaceOnCouch)
    
    def setActiveWorkspace(self, workspace):
        try:
            self.stopAutoLoader()
        except : pass

        if self.active_workspace is not None:
            self.active_workspace.setModelController(None)
        CONF.setLastWorkspace(workspace.name)
        CONF.saveConfig()
        self.active_workspace = workspace
        self.active_workspace.setModelController(self._model_controller)
        self._model_controller.setWorkspace(self.active_workspace)
        self.workspace_persister.setPersister(self.active_workspace, self.active_workspace._dmanager)

        self.report_manager.path = workspace.report_path

        if isinstance(self.active_workspace, WorkspaceOnCouch):
            self.startAutoLoader()
                
    def syncWorkspaces(self):
        """
        Synchronize persistence directory using the DataManager.
        We first make sure that all shared workspaces were added to the repo
        """
        pass
Beispiel #10
0
class WorkspaceManager(object):
    """
    This handles all workspaces. It checks for existing workspaces inside
    the persistence directory.
    It is in charge of starting the WorkspacesAutoSaver to persist each workspace.
    This class stores information in $HOME/.faraday/config/workspacemanager.xml file
    to keep track of created workspaces to be able to load them
    """
    def __init__(self, model_controller, plugin_controller):
        self.active_workspace = None
                                                                  
        self._couchAvailable  = False 
        self.report_manager = ReportManager(10, plugin_controller)
        
        self.couchdbmanager = PersistenceManagerFactory().getInstance()
        self.fsmanager = FSManager()
        
        self._workspaces = {}
        self._workspaces_types = {}
        self._model_controller = model_controller
        self._excluded_directories = [".svn"]
        self.workspace_persister = WorkspacePersister()

    def couchAvailable(self, isit):
        self._couchAvailable = isit

    def _notifyWorkspaceNoConnection(self):
        notifier.showPopup("Couchdb Connection lost. Defaulting to memory. Fix network and try again in 5 minutes.")

    def reconnect(self):
        if not self.reconnectCouchManager():
            self._notifyWorkspaceNoConnection()

    def getCouchManager(self):
        return self.couchdbmanager

    def setCouchManager(self, cm):
        self.couchdbmanager = cm

    @staticmethod
    def getAvailableWorkspaceTypes(): 
        av = [w.__name__ for w in Workspace.__subclasses__() if w.isAvailable() ]
        model.api.devlog("Available wortkspaces: %s" ", ".join(av))
        return av
        
    def reconnectCouchManager(self):
        retval = True
        if not self.couchdbmanager.reconnect():
            retval = False
            return retval
        WorkspacePersister.reExecutePendingActions() 
        return retval
    
    def startAutoLoader(self): 
        pass

    def stopAutoLoader(self):
        pass
    

    def startReportManager(self):
        self.report_manager.start()
    
    def stopReportManager(self):
        self.report_manager.stop()
        self.report_manager.join()
        
    def getActiveWorkspace(self):
        return self.active_workspace
    
    def saveWorkspaces(self):
        pass
            
    def addWorkspace(self, workspace):
        self._workspaces[workspace.name] = workspace
 
    def createVisualizations(self):
        stat = False
        url = ""
        if self.couchdbmanager.isAvailable():
            stat = True
            url  = self.couchdbmanager.pushReports()
        else:
            self._notifyNoVisualizationAvailable()
        return stat, url

    def _notifyNoVisualizationAvailable(self):
        notifier.showPopup("No visualizations available, please install and configure CouchDB")

    def createWorkspace(self, name, description="", workspaceClass = None, shared=CONF.getAutoShareWorkspace(),
                        customer="", sdate=None, fdate=None):

        model.api.devlog("Creating Workspace")
        if self.getWorkspaceType(name) in globals():
            workspaceClass = globals()[self.getWorkspaceType(name)]
        elif not workspaceClass:
            # Defaulting =( 
            model.api.devlog("Defaulting to WorkspaceOnFS") 
            workspaceClass = WorkspaceOnFS

        w = workspaceClass(name, self, shared)
        # Register the created workspace type:
        self._workspaces_types[name] = workspaceClass.__name__
        w.description = description
        w.customer = customer
        if sdate is not None:
            w.start_date = sdate
        if fdate is not None:
            w.finish_date = fdate
        self.addWorkspace(w)
        return w

    def removeWorkspace(self, name):
        work = self.getWorkspace(name)
        if not work: return
        dm = work.getDataManager()
        dm.removeWorkspace(name)
                       
        datapath = CONF.getDataPath()
        todelete = [i for i in os.listdir(datapath) if name in i ]
        for i in todelete:
            os.remove(os.path.join(datapath, i))

        shutil.rmtree(self.getWorkspace(name).getReportPath())
        del self._workspaces[name]
        if self.getWorkspace(name) == self.getActiveWorkspace() and self.getWorkspacesCount() > 0: 
            self.setActiveWorkspace(self.getWorkspace(self._workspaces.keys()[0]))

    def getWorkspace(self, name):
        ''' May return None '''
        if not self._workspaces.get(name):
            # Retrieve the workspace
            self.loadWorkspace(name) 
        return  self._workspaces.get(name)

    def loadWorkspace(self, name): 
        workspaceClass = None
        workspace = None
        if name in self.fsmanager.getWorkspacesNames():
            workspace = self.createWorkspace(name, workspaceClass = WorkspaceOnFS) 
        elif name in self.couchdbmanager.getWorkspacesNames():
            workspace = self.createWorkspace(name, workspaceClass = WorkspaceOnCouch)

        return workspace

    def openWorkspace(self, name):
        w = self.getWorkspace(name)
        self.setActiveWorkspace(w)
        return w
        
    def getWorkspaces(self):
        """
        Simply returns a list of all existing workspaces (including the active one)
        """
        self.loadWorkspaces()
        return [w for w in self._workspaces.itervalues()]
    
    def getWorkspacesCount(self):
        return len(self._workspaces)

    def getWorkspacesNames(self):
        return self._workspaces.keys()
        
    def loadWorkspaces(self): 

        self._workspaces_types = {}
        fsworkspaces = {name: None for name in self.fsmanager.getWorkspacesNames()}
        self._workspaces.update(fsworkspaces)
        couchworkspaces = {name: None for name in self.couchdbmanager .getWorkspacesNames()
                                                if not name == 'reports'}
        self._workspaces.update(couchworkspaces)

        self._workspaces_types.update({name: WorkspaceOnFS.__name__  for name in fsworkspaces})
        self._workspaces_types.update({name: WorkspaceOnCouch.__name__  for name in couchworkspaces})

    def getWorkspaceType(self, name):
        return self._workspaces_types.get(name, 'undefined')
 
    def setActiveWorkspace(self, workspace):
        try:
            self.stopAutoLoader()
        except : pass

        if self.active_workspace is not None:
            self.active_workspace.setModelController(None)
        CONF.setLastWorkspace(workspace.name)
        CONF.saveConfig()
        self.active_workspace = workspace
        self.active_workspace.setModelController(self._model_controller)
        self._model_controller.setWorkspace(self.active_workspace)
        self.workspace_persister.setPersister(self.active_workspace, self.active_workspace._dmanager)

        self.report_manager.path = workspace.report_path

        if isinstance(self.active_workspace, WorkspaceOnCouch):
            self.startAutoLoader()

    def isActive(self, name):
        return self.active_workspace.name == name
                
    def syncWorkspaces(self):
        """
        Synchronize persistence directory using the DataManager.
        We first make sure that all shared workspaces were added to the repo
        """
        pass