# disconnect user before 
<<<<<<< HEAD
<<<<<<< HEAD
        disconnected = self.context.unregisterUserFromXmlrpc(login=dbRows[0]['login'])
=======
        # todo
>>>>>>> 45df48b948e3efe1667629a2b66a7a857a6f5945
=======
        # todo
>>>>>>> upstream1/master
        
        # update password
        emptypwd = hashlib.sha1()
        emptypwd.update( '' )
        sha1 = hashlib.sha1()
        sha1.update( "%s%s" % ( Settings.get( 'Misc', 'salt'), emptypwd.hexdigest() )  )
        
        sql = """UPDATE `%s-users` SET password='******' WHERE id='%s'""" % (prefix, sha1.hexdigest(), userId)
        dbRet, _ = DbManager.instance().querySQL( query = sql )
        if not dbRet: 
            self.error("unable to reset pwd")
            return (self.context.CODE_ERROR, "unable to reset pwd")
            
        return (self.context.CODE_OK, "" )
        
    def updatePwdUserInDB(self, userId, newPwd):
        """
        """
        # init some shortcut
        prefix = Settings.get( 'MySql', 'table-prefix')
        escape = MySQLdb.escape_string
    def __startProcess(self, timeout=20):
        """
        Internal function to start the process
        """
        try:
            if sys.platform == "win32":
                __cmd__ = r'"%s\%s\%s" -interactive -debug -log "%s\selenium2_%s.log"' % (
                    Settings.getDirExec(), Settings.get('Paths', 'bin'),
                    Settings.get('BinWin', 'selenium2'), "%s\%s" %
                    (Settings.getDirExec(), Settings.get('Paths', 'logs')),
                    self.toolName)
                __cmd__ += r' -Dwebdriver.ie.driver="%s\Selenium2\IEDriverServer.exe" ' % (
                    "%s\%s" %
                    (Settings.getDirExec(), Settings.get('Paths', 'bin')))
                __cmd__ += r' -Dwebdriver.chrome.driver="%s\Selenium2\chromedriver.exe" ' % (
                    "%s\%s" %
                    (Settings.getDirExec(), Settings.get('Paths', 'bin')))
                __cmd__ += r' -Dwebdriver.opera.driver="%s\Selenium2\operadriver.exe" ' % (
                    "%s\%s" %
                    (Settings.getDirExec(), Settings.get('Paths', 'bin')))
            else:
                __cmd__ = r'"%s\%s\%s" -interactive -debug -log "%s/selenium_%s.log"' % (
                    Settings.getDirExec(), Settings.get('Paths', 'bin'),
                    Settings.get('BinLinux', 'selenium'), "%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()
def initialize():
    """
    Initialize settings
    """
    Settings.initialize(cfgname='test.ini')
def finalize():
    """
    Finalize settings
    """
    Settings.finalize()
def getInt(section, key):
    """
    Return value as integer according to the key
    """
    return Settings.getInt(section, key)
def get(section, key):
    """
    Return value according to the key
    """
    return Settings.get(section, key)
Exemple #7
0
    def updateUserInDB(self, userId, email=None, login=None, lang=None, 
                       style=None, notifications=None, default=None, 
                       projects=[], level=None):
        """
        """
        self.trace( 'Update user in database Id=%s' % userId )
        
        # init some shortcut
        prefix = Settings.get( 'MySql', 'table-prefix')
        escape = MySQLdb.escape_string
        userId = str(userId)
        
        # search  user by id
        sql = """SELECT * FROM `%s-users` WHERE  id='%s'""" % ( prefix, escape(userId) )
        dbRet, dbRows = DbManager.instance().querySQL( query = sql, columnName=True  )
        if not dbRet: 
            self.error( "unable to search user by id" )
            return (self.context.CODE_ERROR, "unable to read user id")

        sql_values = []
        if login is not None:
            # check if this new login if available ?
            sql = """SELECT * FROM `%s-users` WHERE  login='******' AND id != '%s'""" % ( prefix, escape(login), escape(userId) )
            dbRet, dbRows = DbManager.instance().querySQL( query = sql, columnName=True  )
            if not dbRet: 
                self.error( "unable to search user login" )
                return (self.context.CODE_ERROR, "unable to read user id")
            if len(dbRows): 
                return (self.context.CODE_ALLREADY_EXISTS, "This login already exist")
            else:
                sql_values.append( """login='******'""" % escape(login))
        if email is not None:
            sql_values.append( """email='%s'""" % escape(email))
        if lang is not None:
            sql_values.append( """lang='%s'""" % escape(lang))
        if style is not None:
            sql_values.append( """style='%s'""" % escape(style))
        if notifications is not None:
            sql_values.append( """notifications='%s'""" % escape(notifications))
        if default is not None:
            default = str(default)
            sql_values.append( """defaultproject='%s'""" % escape(default))
            
        # access level
        # the level can not modified for default users (system, admin, monitor and tester)
        if level is not None and int(userId) > 4:
            if level == "admin":  
                sql_values.append( """administrator='1'""")
                sql_values.append( """leader='0'""")
                sql_values.append( """tester='0'""")
                sql_values.append( """developer='0'""")
            elif level == "monitor":
                sql_values.append( """administrator='0'""")
                sql_values.append( """leader='1'""")
                sql_values.append( """tester='0'""")
                sql_values.append( """developer='0'""")
            else:
                sql_values.append( """administrator='0'""")
                sql_values.append( """leader='0'""")
                sql_values.append( """tester='1'""")
                sql_values.append( """developer='1'""")

        # update
        if len(sql_values):
            sql = """UPDATE `%s-users` SET %s WHERE id='%s'""" % (prefix, ','.join(sql_values) , userId)
            dbRet, _ = DbManager.instance().querySQL( query = sql )
            if not dbRet: 
                self.error("unable to update user")
                return (self.context.CODE_ERROR, "unable to update user")
            
        if len(projects):
            # delete relation to update it
            sql = """DELETE FROM `%s-relations-projects` WHERE user_id='%s'""" % (prefix, escape(userId))
            dbRet, _ = DbManager.instance().querySQL( query = sql  )
            if not dbRet: 
                self.error("unable to delete relations")
                return (self.context.CODE_ERROR, "unable to delete relations")
            
            # adding relations-projects`
            sql = """INSERT INTO `%s-relations-projects`(`user_id`, `project_id`) VALUES""" % prefix
            sql_values = []
            for prj in projects:
                sql_values.append( """('%s', '%s')""" % (userId, prj) )
            
            sql += ', '.join(sql_values)
            dbRet, _ = DbManager.instance().querySQL( query = sql, insertData=True  )
            if not dbRet: 
                self.error("unable to insert relations")
                return (self.context.CODE_ERROR, "unable to insert relations")
        
        # new in v19, refresh the cache
        self.loadCache()
        
        return (self.context.CODE_OK, "" )
Exemple #8
0
    def addUserToDB(self, level, login, password, email, lang, 
                    style, notifications, defaultPrj, listPrjs):
        """
        Add a new user in database
        """
        self.trace( 'Add user in database Login=%s' % login )
        
        # init some shortcut
        prefix = Settings.get( 'MySql', 'table-prefix')
        escape = MySQLdb.escape_string
        
        # find user by name
        sql = """SELECT * FROM `%s-users` WHERE login='******'""" % ( prefix, escape(login) )
        dbRet, dbRows = DbManager.instance().querySQL( query = sql, columnName=True  )
        if not dbRet: 
            self.error( "unable to read user by name" )
            return (self.context.CODE_ERROR, "unable to read user by name")
        if len(dbRows): return (self.context.CODE_ALREADY_EXISTS, "this user name already exists")

        # access level
        if level == "admin":
            admin=1
        elif level == "monitor":
            monitor=1
        else:
            tester=1
        
        #  password, create a sha1 hash with salt: sha1( salt + sha1(password) )
        sha1_pwd = hashlib.sha1()
        sha1_pwd.update( password.encode("utf8") ) 
        
        sha1 = hashlib.sha1()
        sha1.update( "%s%s" % ( Settings.get( 'Misc', 'salt'), sha1_pwd.hexdigest() )  )

        # create random apikey
        apikey_secret = hexlify(os.urandom(20))
        
        # prepare the sql query
        sql = """INSERT INTO `%s-users`(`login`, `password`, `administrator`, """  % prefix
        sql += """`leader`, `tester`, `developer`, `system`, `email`, `lang`, """
        sql += """`style`, `active`, `default`, `online`, `notifications`, """
        sql += """`defaultproject`, `cli`, `gui`, `web`, `apikey_id`, `apikey_secret`)"""
        sql += """ VALUES('%s', '%s', '0', """ % (escape(login), escape(sha1.hexdigest()))
        sql += """'0', '1', '0', '0', '%s', '%s',""" % ( escape(email), escape(lang) )
        sql += """'%s', '1', '0', '0', '%s', """ % (escape(style), escape(notifications))
        sql += """'%s', '1', '1', '1', '%s', '%s')""" % (defaultPrj, escape(login), apikey_secret )
        dbRet, lastRowId = DbManager.instance().querySQL( query = sql, insertData=True  )
        if not dbRet: 
            self.error("unable to insert user")
            return (self.context.CODE_ERROR, "unable to insert user")
        
        # adding relations-projects`
        sql = """INSERT INTO `%s-relations-projects`(`user_id`, `project_id`) VALUES""" % prefix
        sql_values = []
        for prj in listPrjs:
            sql_values.append( """('%s', '%s')""" % (lastRowId, prj) )
        
        sql += ', '.join(sql_values)
        dbRet, _ = DbManager.instance().querySQL( query = sql, insertData=True  )
        if not dbRet: 
            self.error("unable to insert relations")
            return (self.context.CODE_ERROR, "unable to insert relations")
                
        # new in v19, refresh the cache
        self.loadCache()
        
        return (self.context.CODE_OK, "%s" % int(lastRowId) )
Exemple #9
0
 def trace(self, txt):
     """
     Trace message
     """
     if Settings.get( 'Trace', 'debug-level') == 'VERBOSE':
         Logger.ClassLogger.trace(self, txt="PSI - %s" % txt)
Exemple #10
0
    def createResultLog(self, testsPath, logPath, logName, logData):
        """
        Create result log
        """
        self.trace("create result log=%s to %s" % (logName, logPath))
        try:
            # write the file
            f = open("%s/%s/%s" % (testsPath, logPath, logName), 'wb')
            f.write(base64.b64decode(logData))
            f.close()

            # notify all users
            size_ = os.path.getsize("%s/%s/%s" % (testsPath, logPath, logName))
            # extract project id
            if logPath.startswith('/'): logPath = logPath[1:]
            tmp = logPath.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": logName,
                            'size': str(size_)
                        }]
                    }]
                }]
                notif = {}
                notif['archive'] = m
                notif['stats-repo-archives'] = {
                    'nb-zip': 1,
                    'nb-trx': 0,
                    'nb-tot': 1,
                    'mb-used': self.getSizeRepoV2(folder=self.testsPath),
                    'mb-free': self.freeSpace(p=self.testsPath)
                }
                data = ('archive', (None, notif))
                ESI.instance().notifyByUserAndProject(body=data,
                                                      admin=True,
                                                      leader=False,
                                                      tester=True,
                                                      developer=False,
                                                      projectId="%s" %
                                                      projectId)

        except Exception as e:
            self.error("unable to create result log: %s" % e)
            return False
        return True
Exemple #11
0
    def createZip(self, trPath, projectId=1):
        """
        Create a zip 

        @type  mainPathTozip:
        @param mainPathTozip:   

        @type  subPathTozip:
        @param subPathTozip:

        @return: response code
        @rtype: int
        """
        ret = self.context.CODE_ERROR
        mainPathTozip, subPathTozip = trPath.split("/", 1)
        try:
            timeArch, milliArch, testName, testUser = subPathTozip.split(".")
            fulltestNameDecoded = base64.b64decode(testName)
            logIndex = self.getLastLogIndex(pathZip=trPath,
                                            projectId=projectId)
            tmp = fulltestNameDecoded.rsplit('/', 1)
            if len(tmp) == 2:
                testNameDecoded = tmp[1]
            else:
                testNameDecoded = tmp[0]
            fileName = 'logs%s_%s_%s_0' % (str(logIndex), testNameDecoded,
                                           self.getTimestamp())
            self.trace("zip %s to %s.zip" % (trPath, fileName))
            zipped = self.toZip(file="%s/%s/%s" %
                                (self.testsPath, projectId, trPath),
                                filename="%s/%s/%s/%s.zip" %
                                (self.testsPath, projectId, trPath, fileName),
                                fileToExclude=['%s.zip' % fileName],
                                keepTree=False)
            ret = zipped
            if zipped == self.context.CODE_OK:
                self.info("zip successfull: %s" % fileName)
                if Settings.getInt('Notifications', 'archives'):
                    # now notify all connected users
                    size_ = os.path.getsize(
                        "%s/%s/%s/%s.zip" %
                        (self.testsPath, projectId, trPath, fileName))
                    m = [{
                        "type":
                        "folder",
                        "name":
                        mainPathTozip,
                        "project":
                        "%s" % projectId,
                        "content": [{
                            "type":
                            "folder",
                            "name":
                            subPathTozip,
                            "project":
                            "%s" % projectId,
                            "content": [{
                                "project": "%s" % projectId,
                                "type": "file",
                                "name": '%s.zip' % fileName,
                                'size': str(size_)
                            }]
                        }]
                    }]
                    notif = {}
                    notif['archive'] = m
                    notif['stats-repo-archives'] = {
                        'nb-zip': 1,
                        'nb-trx': 0,
                        'nb-tot': 1,
                        'mb-used': self.getSizeRepoV2(folder=self.testsPath),
                        'mb-free': self.freeSpace(p=self.testsPath)
                    }

                    data = ('archive', (None, notif))
                    ESI.instance().notifyByUserTypes(body=data,
                                                     admin=True,
                                                     leader=False,
                                                     tester=True,
                                                     developer=False)
            else:
                self.error("zip %s failed" % trPath)
        except Exception as e:
            raise Exception("[createZip] %s" % str(e))
        return ret