Ejemplo n.º 1
0
    def getInstalled (self, b64=False):
        """
        Returns all registered agents

        @return: all registered agents
        @rtype: list
        """
        self.trace("get agents installed" )
        pluginsInstalled = []
        if os.path.exists( '%s/%s/Embedded/' % ( Settings.getDirExec(), Settings.get( 'Paths', 'tools' )) ):
            files = os.listdir( '%s/%s/Embedded/' % ( Settings.getDirExec(), Settings.get( 'Paths', 'tools' )) )
            for f in files:
                if f.endswith('Agent.py'):
                    a = {}
                    # open plugin to get agent type and description
                    fp = open( '%s/%s/Embedded/%s' % (Settings.getDirExec(), Settings.get( 'Paths', 'tools' ), f) , 'r')
                    data = fp.read()
                    fp.close()
                    #
                    agentType = data.split('__TYPE__="""')
                    if len(agentType) == 2:
                        agentType = agentType[1].split('"""', 1)[0]
                        a['type'] = agentType
                    agentDescr = data.split('__DESCRIPTION__="""')
                    if len(agentDescr) == 2:
                        agentDescr = agentDescr[1].split('"""', 1)[0]
                        a['description'] = agentDescr
                    if  len(a) > 0:
                        pluginsInstalled.append( a )
        return pluginsInstalled
Ejemplo n.º 2
0
    def __init__(self, context, taskmgr):
        """
        Repository manager for archives files
        """
        RepoManager.RepoManager.__init__(
            self,
            pathRepo='%s%s' %
            (Settings.getDirExec(), Settings.get('Paths', 'testsresults')),
            extensionsSupported=[
                RepoManager.TEST_RESULT_EXT, RepoManager.TXT_EXT,
                RepoManager.CAP_EXT, RepoManager.ZIP_EXT, RepoManager.PNG_EXT,
                RepoManager.JPG_EXT
            ],
            context=context)
        self.context = context
        self.taskmgr = taskmgr

        self.prefixLogs = "logs"
        self.prefixBackup = "backuparchives"
        self.destBackup = "%s%s" % (Settings.getDirExec(),
                                    Settings.get('Paths', 'backups-archives'))

        self.cacheUuids = {}
        self.cachingUuid()
        self.trace("nb entries in testresult cache: %s" % len(self.cacheUuids))
Ejemplo n.º 3
0
    def __init__(self,
                 listeningAddress,
                 agentName='ESI',
                 sslSupport=False,
                 wsSupport=False,
                 context=None):
        """
        Event server interface

        @param listeningAddress:
        @type listeningAddress:

        @param agentName: agent name used on request
        @type agentName: string
        """
        NetLayerLib.ServerAgent.__init__(
            self,
            listeningAddress=listeningAddress,
            agentName=agentName,
            keepAliveInterval=Settings.getInt('Network', 'keepalive-interval'),
            inactivityTimeout=Settings.getInt('Network', 'inactivity-timeout'),
            responseTimeout=Settings.getInt('Network', 'response-timeout'),
            selectTimeout=Settings.get('Network', 'select-timeout'),
            sslSupport=sslSupport,
            wsSupport=wsSupport,
            certFile='%s/%s' %
            (Settings.getDirExec(),
             Settings.get('Client_Channel', 'channel-ssl-cert')),
            keyFile='%s/%s' %
            (Settings.getDirExec(),
             Settings.get('Client_Channel', 'channel-ssl-key')),
            pickleVer=Settings.getInt('Network', 'pickle-version'))
        self.__mutex__ = threading.RLock()
        self.context = context
Ejemplo n.º 4
0
    def stopping(self):
        """
        On stopping the server
        """
        self.info("Stopping server...")

        # cleanup all child processes
        for f in os.listdir(
                "%s/%s" %
            (Settings.getDirExec(), Settings.get('Paths', 'run'))):
            if f.endswith(".pid"):
                pid = f.split(".pid")[0]

                # kill the process
                if pid.isdigit():
                    self.info('Stopping chid processes %s...' % pid)
                    try:
                        while 1:
                            os.kill(int(pid), signal.SIGTERM)
                            time.sleep(0.1)
                    except OSError as err:
                        pass
                    time.sleep(1)
                    # just to be sure, delete a second time
                    try:
                        os.remove("%s/%s/%s.pid" %
                                  (Settings.getDirExec(),
                                   Settings.get('Paths', 'run'), pid))
                    except Exception as e:
                        pass
Ejemplo n.º 5
0
    def run(self):
        """
        On running thread
        """
        self.parent.onToolLogWarningCalled("Starting UIautomator on device...")

        __adbexe__ = r'%s\\Plugins\\adb\\bin\\adb.exe' % Settings.getDirExec()
        __adbbin__ = r'%s\\Plugins\\adb\\bin\\' % Settings.getDirExec()
        
        self.trace("uploading jar files on devices")
        __cmd__ = '"%s" push "%s\\Adb\\bundle.jar" /data/local/tmp/' % (__adbexe__, __adbbin__ )
        ret = subprocess.call(  __cmd__, shell=True, 
                                stdin=subprocess.PIPE, 
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
        self.trace("uploading ret: %s" % ret)
        
        __cmd__ = '"%s" push "%s\\Adb\\uiautomator-stub.jar" /data/local/tmp/' % (__adbexe__,  __adbbin__)
        ret = subprocess.call(  __cmd__, shell=True, 
                                stdin=subprocess.PIPE, 
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
        self.trace("uploading ret: %s" % ret)

        __cmd__ = r'"%s" shell uiautomator runtest uiautomator-stub.jar bundle.jar -c com.github.uiautomatorstub.Stub' % __adbexe__
        self.parent.trace(__cmd__)
        try:
            self.uiProcess = subprocess.Popen(  __cmd__, shell=True, 
                                                stdin=subprocess.PIPE, 
                                                stdout=subprocess.PIPE,
                                                stderr=subprocess.STDOUT,
                                                bufsize=0 )
            pid = self.uiProcess.pid
            self.parent.trace("UIautomator thread started with pid=%s" % pid)
            if sys.version_info > (3,):
                ret, lines = self.readData(prompt=b'INSTRUMENTATION_STATUS_CODE: 1', maxTimeout=10)
            else:
                ret, lines = self.readData(prompt='INSTRUMENTATION_STATUS_CODE: 1', maxTimeout=10) 
            if ret:
                self.parent.trace("prompt uiautomator detected")
         
                self.parent.onToolLogWarningCalled("UIautomator is started")
                
                
                __cmd__ = '"%s" forward tcp:%s tcp:%s' % (__adbexe__, 
                                                          self.parent.localPort, 
                                                          self.parent.devicePort )
                self.trace("activate forward: %s" % __cmd__)
                ret = subprocess.call(__cmd__, shell=True)
                self.trace("%s" % ret)

                self.parent.startScreenCapture()

                self.isStarted = True                                 
            else:
                self.parent.onToolLogErrorCalled("Unable to start UIautomator")
        except Exception as e:
            self.parent.onToolLogErrorCalled("Unable to start UIautomator")
            self.parent.error( "Unable to start UIautomator: %s" % str(e))  
            self.parent.onResetAgentCalled()
Ejemplo n.º 6
0
    def __init__(self, context, taskmgr):
        """
        Construct Adpaters Manager
        """
        RepoManager.RepoManager.__init__(
            self,
            pathRepo='%s/%s/' %
            (Settings.getDirExec(), Settings.get('Paths', 'adapters')),
            extensionsSupported=[RepoManager.PY_EXT, RepoManager.TXT_EXT],
            context=context)

        self.context = context
        self.taskmgr = taskmgr
        self.__pids__ = {}
        self.prefixBackup = "backupadapters"
        self.destBackup = "%s%s" % (Settings.getDirExec(),
                                    Settings.get('Paths', 'backups-adapters'))
        self.embeddedPath = "%s/%s/%s" % (Settings.getDirExec(),
                                          Settings.get('Paths', 'packages'),
                                          Settings.get('Paths', 'adapters'))

        # Initialize the repository
        self.info('Deploying sut adapters ...')
        deployed = self.deploy()
        if deployed:
            self.info("All sut adapters deployed")

        # update main init file
        self.updateMainInit()

        # cleanup all lock files on init
        self.cleanupLocks()
    def __init__ (self, listeningAddress, agentName = 'PSI', sslSupport=False, wsSupport=False, context=None):
        """
        Construct Probe Server Interface

        @param listeningAddress:
        @type listeningAddress:

        @param agentName:
        @type agentName: string
        """
        NetLayerLib.ServerAgent.__init__(self, listeningAddress = listeningAddress, agentName = agentName,
                                            keepAliveInterval= Settings.getInt('Network', 'keepalive-interval' ), 
                                            inactivityTimeout=Settings.getInt( 'Network', 'inactivity-timeout' ),
                                            responseTimeout=Settings.getInt( 'Network', 'response-timeout' ),
                                            selectTimeout=Settings.get( 'Network', 'select-timeout' ),
                                            sslSupport=sslSupport,
                                            wsSupport=wsSupport,
                                            certFile='%s/%s' % (Settings.getDirExec(),
                                                                Settings.get( 'Probe_Channel', 'channel-ssl-cert' )), 
                                            keyFile='%s/%s' % (Settings.getDirExec(),
                                                               Settings.get( 'Probe_Channel', 'channel-ssl-key' )),
                                            pickleVer=Settings.getInt( 'Network', 'pickle-version' )
                                        )
        self.context = context
        self.__mutex = threading.RLock()
        self.probesRegistered = {}
        self.probesPublicIp = {}
Ejemplo n.º 8
0
 def prepareDaemon(self):
     """
     Prepare daemon
     """
     if not Settings.cfgFileIsPresent():
         sys.stdout.write(" (config file doesn't exist)")
         sys.exit(2)
     try:
         # Initialize
         Settings.initialize()
         Logger.initialize()
         CliFunctions.initialize(parent=self)
     except Exception as e:
         self.error("Unable to initialize settings: %s" % str(e))
     else:
         # config file exist so prepare the deamon
         self.prepare(
             pidfile="%s/%s/%s.pid" %
             (Settings.getDirExec(), Settings.get(
                 'Paths', 'run'), Settings.get('Server', 'acronym')),
             name=Settings.get('Server', 'name'),
             stdout="%s/%s/output.log" %
             (Settings.getDirExec(), Settings.get('Paths', 'logs')),
             stderr="%s/%s/output.log" %
             (Settings.getDirExec(), Settings.get('Paths', 'logs')),
             stdin="/dev/null",
             runningfile="%s/%s/%s.running" %
             (Settings.getDirExec(), Settings.get(
                 'Paths', 'run'), Settings.get('Server', 'acronym')),
         )
Ejemplo n.º 9
0
    def __startProcess(self, timeout=20):
        """
        Internal function to start the process
        """
        try:
            if sys.platform == "win32":
                __cmd__ = r'"%s" -interactive -debug -log "%s\selenium2_%s.log"' % (
                    BIN_WIN, "%s\%s" %
                    (Settings.getDirExec(), Settings.get('Paths', 'logs')),
                    self.toolName)
                __cmd__ += r' -Dwebdriver.ie.driver="%s\Plugins\selenium2server\bin\IEDriverServer.exe" ' % (
                    Settings.getDirExec())
                __cmd__ += r' -Dwebdriver.chrome.driver="%s\Plugins\selenium2server\bin\chromedriver.exe" ' % (
                    Settings.getDirExec())
                __cmd__ += r' -Dwebdriver.opera.driver="%s\Plugins\selenium2server\bin\operadriver.exe" ' % (
                    Settings.getDirExec())
            else:
                __cmd__ = r'"%s" -interactive -debug -log "%s/selenium_%s.log"' % (
                    BIN_LINUX, "%s\%s" %
                    (Settings.getDirExec(), Settings.get('Paths', 'logs')),
                    self.toolName)
            self.trace("external program called: %s" % __cmd__)

            self.seleniumProcess = subprocess.Popen(__cmd__,
                                                    stdin=subprocess.PIPE,
                                                    stdout=subprocess.DEVNULL,
                                                    stderr=subprocess.STDOUT,
                                                    shell=True)
            self.trace("Selenium Server thread started Pid=%s" %
                       self.seleniumProcess.pid)

            # checking if the server is properly started
            currentTime = startedTime = time.time()
            started = False
            while ((currentTime - startedTime) < timeout):
                try:
                    requestlib.urlopen(self.urlHost).read()
                except Exception as err:
                    currentTime = time.time()
                    time.sleep(2.0)
                    continue
                started = True
                break
            if not started:
                raise RuntimeError('Start Selenium java process failed!')
            else:
                time.sleep(2.0)
                self.trace("start ok")
                self.onToolLogWarningCalled("Selenium Server is started")
                self.onPluginStarted()

        except Exception as e:
            self.onToolLogErrorCalled("Unable to start Selenium Server")
            self.error("unable to start Selenium Server: %s" % str(e))
            self.onResetAgentCalled()
Ejemplo n.º 10
0
 def getUsage(self, b64=False):
     """
     Return usage
     """
     ret = {}
     try:
         ret['disk-usage'] = self.diskUsage(p=Settings.getDirExec())
         ret['disk-usage-logs'] = self.getSize(
             folder="%s/%s" %
             (Settings.getDirExec(), Settings.get('Paths', 'logs')))
         ret['disk-usage-tmp'] = self.getSize(
             folder="%s/%s" %
             (Settings.getDirExec(), Settings.get('Paths', 'tmp')))
         ret['disk-usage-testresults'] = self.getSize(
             folder="%s/%s" %
             (Settings.getDirExec(), Settings.get('Paths', 'testsresults')))
         ret['disk-usage-adapters'] = self.getSize(
             folder="%s/%s" %
             (Settings.getDirExec(), Settings.get('Paths', 'adapters')))
         ret['disk-usage-libraries'] = self.getSize(
             folder="%s/%s" %
             (Settings.getDirExec(), Settings.get('Paths', 'libraries')))
         ret['disk-usage-backups'] = self.getSize(
             folder="%s/%s" %
             (Settings.getDirExec(), Settings.get('Paths', 'backups')))
         ret['disk-usage-tests'] = self.getSize(
             folder="%s/%s" %
             (Settings.getDirExec(), Settings.get('Paths', 'tests')))
     except Exception as e:
         self.error("unable to get server usage: %s" % e)
     return ret
Ejemplo n.º 11
0
    def __getScreen(self):
        """
        Internal function to retreive the screen from the device
        """
        __adbexe__ = r'%s\\Plugins\\adb\\bin\\adb.exe' % Settings.getDirExec()
        __ret__ = '%s\screncapture.png' % self.getTemp()
        __ret2__ = '%s\layout.xml' % self.getTemp()  
        __cmd__ = '"%s" pull /data/local/tmp/screncapture.png "%s"' % ( __adbexe__, __ret__)
        __cmd2__ = '"%s" pull /data/local/tmp/local/tmp/layout.xml "%s"' % ( __adbexe__, __ret2__)
        
        req = urllib2.Request('http://127.0.0.1:%s/jsonrpc/0' % self.localPort )
        req.add_header('Content-Type', 'application/json; charset=utf-8')
        try:
            response = urllib2.urlopen(req, b'{"jsonrpc":"2.0","method":"takeScreenshot","id":1, "params": [ "screncapture.png", 1.0, 90] }' )
            
            response2 = urllib2.urlopen(req, b'{"jsonrpc":"2.0","method":"dumpWindowHierarchy","id":1, "params": [ true, "layout.xml" ] }' )
            subprocess.call(__cmd2__, shell=True, 
                            stdin=subprocess.PIPE, 
                            stdout=subprocess.PIPE, 
                            stderr=subprocess.STDOUT)

        except Exception as e:
            self.error("error on adb get screen thread: %s" % e )
        else:
        
            ret = subprocess.call(  __cmd__, shell=True,
                                    stdin=subprocess.PIPE, 
                                    stdout=subprocess.PIPE, 
                                    stderr=subprocess.STDOUT)
            if not ret:
                self.onScreenCaptured(filename=__ret__,xml=__ret2__)
Ejemplo n.º 12
0
    def run(self):
        """
        On run function
        """
        __cmd__ = r'"%s\Plugins\adb\bin\run.bat"' % Settings.getDirExec()
        self.parent.trace(__cmd__)
        try:
            self.adbProcess = subprocess.Popen( __cmd__, shell=True, 
                                                stdin=subprocess.PIPE, 
                                                stdout=subprocess.PIPE, 
                                                stderr=subprocess.STDOUT, bufsize=0 )
            pid = self.adbProcess.pid
            self.parent.trace("Adb thread started with pid=%s" % pid)
            if sys.version_info > (3,):
                ret, lines = self.readData(prompt=b'OK', maxTimeout=30)
            else:
                ret, lines = self.readData(prompt='OK', maxTimeout=30) 
            if ret:
                self.parent.trace("prompt adb detected")
         
                self.parent.onToolLogWarningCalled("Adb is started")
                
                self.parent.onPluginStarted()
                self.parent.startUiautomator()

                self.isStarted = True                                 
            else:
                self.parent.onToolLogErrorCalled("Unable to start ADB")
        except Exception as e:
            self.parent.onToolLogErrorCalled("Unable to start ADB server")
            self.parent.error( "Unable to start adb server: %s" % str(e))  
            self.parent.onResetAgentCalled()
Ejemplo n.º 13
0
    def __init__(self):
        """
        Construct toolbox Manager
        """
        self.pkgsToolsPath = "%s/%s/%s/linux2/" % (
            Settings.getDirExec(), Settings.get(
                'Paths', 'packages'), Settings.get('Paths', 'tools'))

        self.info('Detecting local tools to deploy...')
        pkg = self.preInstall()
        if Settings.getInt('WebServices', 'local-tools-enabled'):
            if pkg is not None:
                self.info('Deploying local tools %s...' % pkg)
                self.installPkgV2(pkgName=pkg)

        self.TOOLS_INSTALLED = False
        try:
            import Toolbox
            self.TOOLS_INSTALLED = True
            self.info("Local tools are installed")
        except Exception as e:
            self.info("Local tools are NOT installed")
            self.trace("More details: %s" % unicode(e).encode('utf-8'))
        self.configsFile = None
        self.__pids__ = {}
    def __init__(self, controllerIp, controllerPort, toolName, toolDesc, defaultTool, 
                supportProxy=0, proxyIp=None, proxyPort=None, sslSupport=True):
        """
        Ssh agent

        @param controllerIp: controller ip/host
        @type controllerIp: string

        @param controllerPort: controller port
        @type controllerPort: integer

        @param toolName: agent name
        @type toolName: string

        @param toolDesc: agent description
        @type toolDesc: string

        @param defaultTool: True if the agent is started by the server, False otherwise
        @type defaultTool: boolean
        """
        GenericTool.Tool.__init__(self, controllerIp, controllerPort, toolName, toolDesc, 
                    defaultTool, supportProxy=supportProxy, proxyIp=proxyIp, 
                    proxyPort=proxyPort, sslSupport=sslSupport)
        
        self.__type__ = __TYPE__
        if EXT_SSH_LIB_INSTALLED: 
            paramiko.util.log_to_file( "%s/%s/sshlog_%s.txt" % (Settings.getDirExec(), 
                                                                Settings.get( 'Paths', 'logs' ), 
                                                                toolName) )
Ejemplo n.º 15
0
    def addPyInitFile(self, pathFile, descr="", helper="", allmodules=""):
        """
        Add the default __init__ file of the repository

        @type  archivePath:
        @param archivePath:

        @type  descr:
        @param descr:

        @return: 
        @rtype: 
        """
        HEADER = ''
        tpl_path = "%s/%s/library_header.tpl" % ( Settings.getDirExec(), 
                                                  Settings.get( 'Paths', 'templates' ) )
        try:
            fd = open( tpl_path , "r")
            HEADER = fd.read()
            fd.close()
        except Exception as e:
            self.error( 'unable to read template library header: %s' % str(e) )

        try:
            default_init = MAIN_INIT % (HEADER, descr, helper, allmodules)
            f = open( '%s/__init__.py' % pathFile, 'w')
            f.write( default_init )
            f.close()
        except Exception as e:
            self.error( e )
            return False
        return True
Ejemplo n.º 16
0
 def __startProcess(self, timeout=20):
     """
     Internal function to start the process
     """
     try:
         if sys.platform == "win32" :
             __cmd__ = r'"%s\%s\%s" -jar ' % (   Settings.getDirExec(), 
                                                 Settings.get( 'Paths', 'bin' ), 
                                                 Settings.get( 'BinWin', 'selenium3' ) )
             __cmd__ += r' -Dwebdriver.ie.driver="%s\Selenium3\IEDriverServer.exe" ' % (
                                                                             "%s\%s" % ( Settings.getDirExec(), 
                                                                                         Settings.get( 'Paths', 'bin' ))
                                                                             )
             __cmd__ += r' -Dwebdriver.chrome.driver="%s\Selenium3\chromedriver.exe" ' % (
                                                                             "%s\%s" % ( Settings.getDirExec(), 
                                                                                         Settings.get( 'Paths', 'bin' ))
                                                                             )
             __cmd__ += r' -Dwebdriver.opera.driver="%s\Selenium3\operadriver.exe" ' % (
                                                                             "%s\%s" % ( Settings.getDirExec(), 
                                                                                         Settings.get( 'Paths', 'bin' ))
                                                                             )
             __cmd__ += r' -Dwebdriver.gecko.driver="%s\Selenium3\geckodriver.exe" ' % (
                                                                             "%s\%s" % ( Settings.getDirExec(), 
                                                                                         Settings.get( 'Paths', 'bin' ))
                                                                             )
             __cmd__ += r' -Dwebdriver.edge.driver="%s\Selenium3\MicrosoftWebDriver.exe" ' % (
                                                                             "%s\%s" % ( Settings.getDirExec(), 
                                                                                         Settings.get( 'Paths', 'bin' ))
                                                                             )
                                                                             
             __cmd__ +=  r' "%s\Selenium3\selenium-server-standalone.jar"' % (
                                                                             "%s\%s" % ( Settings.getDirExec(), 
                                                                                         Settings.get( 'Paths', 'bin' ))
                                                                             )
Ejemplo n.º 17
0
    def generateFromWSDL(self, wsdlUrl, wsdlFile, pkg, overwrite=False):
        """
        Generate adapter from wsdl
        """
        self.trace("Generating adapter form wsdl..." )
        ret = False
        try:
            wsdl = wsdlUrl
            f = None
            if len(wsdlFile):
                self.trace("mode read from file")
                wsdlDecoded = base64.b64decode(wsdlFile)
                f = tempfile.NamedTemporaryFile(delete=False)
                f.write(wsdlDecoded)
                f.close()
                
                wsdl = f.name
                
            __cmd__ = '%s %s/Scripts/generate-wsdl-adapter.py --wsdl="%s" --pkg="%s" --pathlib="%s"' % ( 
                                                            Settings.get( 'Bin', 'python' ),
                                                            Settings.getDirExec(),
                                                            wsdl, 
                                                            pkg,
                                                            Settings.getDirExec()
                                                        )
            if overwrite:
                __cmd__ += ' --overwrite'
            self.trace( __cmd__ )
            __cmd_args__ = shlex.split(__cmd__)
            p = subprocess.Popen( __cmd_args__, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
            out, err = p.communicate()
            if out:
                self.trace( "WSDL generator (out): %s" % out )
            if err:
                self.error( "WSDL generator (err): %s" % err )
            if p.returncode >= 1:
                self.error('Unable to make adp from wsdl')
            else:
                self.info('Adapter generated successfully')
                ret = True

        except Exception as e:
            self.error( "unable to generate adapter from wsdl: %s" % e )

        return ret
Ejemplo n.º 18
0
 def getGeneric(self):
     """
     Return generic default libraries package
     """
     settings_file = ConfigParser.ConfigParser()
     settings_file.read( "%s/settings.ini" % Settings.getDirExec() )
     defaultPkg = settings_file.get("Default", "generic-libraries" )
     del settings_file
     return defaultPkg
Ejemplo n.º 19
0
 def __init__(self, context):
     """
     Construct Probes Manager
     """
     self.pkgsProbesPath = "%s/%s/%s/linux2/" % ( Settings.getDirExec(),   Settings.get( 'Paths', 'packages' ), 
                                     Settings.get( 'Paths', 'probes' ) )
     self.context = context
     self.configsFile = None
     self.__pids__ = {}
Ejemplo n.º 20
0
 def __init__(self):
     """
     Repository manager log reports files
     """
     RepoManager.RepoManager.__init__(self,
         pathRepo='%s%s' % ( Settings.getDirExec(), Settings.get( 'Paths', 'reports' ) ),
             extensionsSupported = [ RepoManager.TEST_RESULT_EXT, RepoManager.TXT_EXT, 
                                     RepoManager.CAP_EXT, RepoManager.ZIP_EXT,
                                     RepoManager.PNG_EXT ] )
Ejemplo n.º 21
0
 def __init__(self):
     """
     Repository manager for tests files
     """
     RepoManager.RepoManager.__init__(
         self,
         pathRepo='%s%s' %
         (Settings.getDirExec(), Settings.get('Paths', 'public')),
         extensionsSupported=[])
Ejemplo n.º 22
0
    def moveNewFile (self, data):
        """
        Move the file from the temp unix to the test result storage
        Deprecated function thanks to the migration to python3 on probe side
        
        @type  data:
        @param data:
        """
        self.trace(" moving file" )
        try:
            testResult = data['result-path']
            fileName = data['filename']
            self.trace( 'move %s to %s' % ( fileName, testResult ) )
            # move file 
            testsResultPath = '%s%s' % (    Settings.getDirExec(),Settings.get( 'Paths', 'testsresults' ) )
            
            shutil.copyfile(    src = '/tmp/%s' % fileName,
                                dst = '%s/%s/%s' % (testsResultPath, testResult, fileName)
                            )
        except Exception as e:
            self.error( "unable to move the new file: %s" % e )
        else:
            try:
                # now notify all connected users
                size_ = os.path.getsize( '%s/%s/%s' % (testsResultPath, testResult, fileName) )
                if testResult.startswith('/'):
                    testResult = testResult[1:]
                tmp = testResult.split('/', 1)
                projectId = tmp[0]
                tmp = tmp[1].split('/', 1)
                mainPathTozip= tmp[0]
                subPathTozip = tmp[1]
                if Settings.getInt( 'Notifications', 'archives'):
                    m = [   {   "type": "folder", "name": mainPathTozip, "project": "%s" % projectId,
                                "content": [ {  "type": "folder", "name": subPathTozip, "project": "%s" % projectId,
                                "content": [ { "project": "%s" % projectId, "type": "file", "name": fileName, 'size': str(size_) } ]} ] }  ]
                    notif = {}
                    notif['archive'] = m 
                    notif['stats-repo-archives'] = {    'nb-zip':1, 'nb-trx':0, 'nb-tot': 1,
                                                    'mb-used': RepoArchives.instance().getSizeRepo(folder=RepoArchives.instance().testsPath),
                                                    'mb-free': RepoArchives.instance().freeSpace(p=RepoArchives.instance().testsPath) }
                    data = ( 'archive', ( None, notif) )    

                    ESI.instance().notifyByUserAndProject(body = data, 
                                                          admin=True, 
                                                          monitor=False, 
                                                          tester=True, 
                                                          projectId="%s" % projectId)
        
            except Exception as e:
                self.error( "unable to notify users for this new file: %s" % e )
        
        # clean temp dir
        try:
            os.remove( '/tmp/%s' % fileName )
        except Exception as e:
            pass
Ejemplo n.º 23
0
    def checkGlobalSyntax(self):
        """
        Check syntax and more of all adapters

        @return: 
        @rtype: tuple
        """
        __cmd__ = "%s %s/Core/docgenerator.py %s %s False False True True" % (
            Settings.get('Bin', 'python'), Settings.getDirExec(),
            Settings.getDirExec(), "%s/%s" %
            (Settings.getDirExec(), Settings.get('Paths', 'tmp')))
        p = os.popen(__cmd__)
        msg_err = p.readlines()
        if len(msg_err) == 0:
            return True, ''
        else:
            msg_err = '\n'.join(msg_err).replace(".py", "")
            return False, msg_err
Ejemplo n.º 24
0
 def getDefault(self):
     """
     Return the default adapters package
     """
     settings_file = ConfigParser.ConfigParser()
     settings_file.read("%s/settings.ini" % Settings.getDirExec())
     defaultPkg = settings_file.get("Default", "current-adapters")
     del settings_file
     return defaultPkg
Ejemplo n.º 25
0
 def getGeneric(self):
     """
     Return the default generic package
     """
     settings_file = ConfigParser.ConfigParser()
     settings_file.read("%s/settings.ini" % Settings.getDirExec())
     defaultPkg = settings_file.get("Default", "generic-adapters")
     del settings_file
     return defaultPkg
Ejemplo n.º 26
0
 def generateSamples(self):
     """
     Generate all tar.gz (samples)
     """
     ret = False
     self.trace('Generating samples...')
     try:
         DEVNULL = open(os.devnull, 'w')
         sys.stdout.write("Generate samples packages...\n")
         __cmd__ = "%s/Scripts/generate-samples.sh %s/Scripts/" % (
             Settings.getDirExec(), Settings.getDirExec())
         subprocess.call(__cmd__,
                         shell=True,
                         stdout=DEVNULL,
                         stderr=DEVNULL)
         ret = True
     except Exception as e:
         self.error("unable to generate sample: %s" % e)
     return ret
Ejemplo n.º 27
0
 def cleanupLocks(self):
     """
     Cleanup all lock files
     """
     ret = False
     self.trace('Cleanup all lock files for libraries...')
     try:
         DEVNULL = open(os.devnull, 'w')
         sys.stdout.write( "Cleanup all lock files for libraries...\n")
         __cmd__ = "%s/Scripts/unlock-libraries.sh %s/Scripts/" % (Settings.getDirExec(), 
                                                                   Settings.getDirExec())
         subprocess.call(__cmd__, shell=True, stdout=DEVNULL, stderr=DEVNULL)  
         ret = True
     except Exception as e:
         self.error("unable to cleanup lock files for libraries: %s" % e)
     
     sys.stdout.flush()
     
     return ret
Ejemplo n.º 28
0
    def getDefaultAgents(self, b64=False):
        """
        Read default agents to start on boot

        @return: agents to start on boot
        @rtype: list
        """
        agents = []
        if not os.path.isfile("%s/agents.ini" % Settings.getDirExec()):
            self.error('config file (agents.ini) is missing')
        else:
            self.configsFile = ConfigParser.ConfigParser()
            self.configsFile.read("%s/agents.ini" % Settings.getDirExec())
            for p in self.configsFile.sections():
                tpl = {'name': p}
                for optKey, optValue in self.configsFile.items(p):
                    tpl[optKey] = optValue
                # {'enable': '1', 'type': 'textual', 'name': 'textual01', 'description': 'default probe'},
                agents.append(tpl)
        return agents
Ejemplo n.º 29
0
    def run(self):
        """
        On running thread
        """
        __adbexe__ = '%s\%s\%s' % (Settings.getDirExec(),
                                   Settings.get('Paths', 'bin'),
                                   Settings.get('BinWin', 'adb-exe'))
        __ret__ = '%s\screncapture.png' % self.parent.getTemp()
        __cmd__ = '"%s" pull /data/local/tmp/screncapture.png "%s"' % (
            __adbexe__, __ret__)
        __ret2__ = '%s\layout.xml' % self.parent.getTemp()
        __cmd2__ = '"%s" pull /data/local/tmp/local/tmp/layout.xml "%s"' % (
            __adbexe__, __ret2__)

        req = urllib2.Request('http://127.0.0.1:%s/jsonrpc/0' %
                              self.parent.localPort)
        req.add_header('Content-Type', 'application/json')

        nbError = 0
        while not self.stopEvent.isSet():
            time.sleep(0.1)

            if self.running:
                try:
                    response = urllib2.urlopen(
                        req,
                        b'{"jsonrpc":"2.0","method":"takeScreenshot","id":1, "params": [ "screncapture.png", 1.0, 90] }'
                    )

                    response2 = urllib2.urlopen(
                        req,
                        b'{"jsonrpc":"2.0","method":"dumpWindowHierarchy","id":1, "params": [ true, "layout.xml" ] }'
                    )
                    subprocess.call(__cmd2__,
                                    shell=True,
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)

                except Exception as e:
                    self.parent.error("error on adb screen thread: %s" % e)
                    nbError += 1
                    if nbError >= MAX_ERROR_SCREEN: self.stop()
                else:

                    ret = subprocess.call(__cmd__,
                                          shell=True,
                                          stdin=subprocess.PIPE,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.STDOUT)
                    if not ret:
                        self.parent.onScreenCaptured(filename=__ret__,
                                                     xml=__ret2__)
    def __init__(self, context):
        """
        Storage data adapters
        """
        RepoManager.RepoManager.__init__(self, pathRepo='%s%s' % (Settings.getDirExec(), Settings.get( 'Paths', 'tmp' )),
                                        context=context)
        self.context = context
        self.prefixAdapters = "adapter"
        self.prefixAdaptersAll = "private_storage"
        self.adpDataPath = "%s/AdaptersData" % self.testsPath

        self.initStorage()