def getUserProfile(self, userId):
        """
        """
        new_profile = {}

        success, user_profile = self.getUserFromDB(userId=userId)
        if success != self.context.CODE_OK:
            return (self.context.CODE_ERROR, {})

        # add level to profile
        if user_profile["administrator"]:
            new_profile["level"] = "Administrator"
        if user_profile["monitor"]:
            new_profile["level"] = "Monitor"
        if user_profile["tester"]:
            new_profile["level"] = "Tester"

        # add some general infos
        new_profile["api_login"] = user_profile["login"]
        new_profile["email"] = user_profile["email"]
        new_profile["api_secret"] = user_profile["apikey_secret"]

        # projects
        sql = """SELECT * FROM `relations-projects` WHERE user_id=?"""
        sql_args = (userId, )
        success, relations_list = DbManager.instance().querySQL(
            query=sql, columnName=True, args=sql_args)
        if not success:
            self.error("unable to read relation's table")
            return (self.context.CODE_ERROR, {})

        sql = """SELECT * FROM `projects` WHERE id=?"""
        sql_args = (relations_list[0]["project_id"], )
        for row_relation in relations_list[1:]:
            sql += """ OR id=?"""
            sql_args += (row_relation['project_id'], )

        success, projects_list = DbManager.instance().querySQL(query=sql,
                                                               columnName=True,
                                                               args=sql_args)

        if not success:
            self.error("unable to read projects according to the user")

            return (self.context.CODE_ERROR, {})

        new_profile["projects"] = projects_list

        # default project
        sql = """SELECT * FROM `projects` WHERE id=?"""
        sql_args = (user_profile["defaultproject"], )
        success, def_project = DbManager.instance().querySQL(query=sql,
                                                             columnName=True,
                                                             args=sql_args)

        if not success:
            self.error("unable to read default project according to the user")
        new_profile["default_project"] = def_project[0]

        return (self.context.CODE_OK, new_profile)
Beispiel #2
0
    def updateVariableInDB(self,
                           variableId,
                           variableName=None,
                           variableValue=None,
                           projectId=None):
        """
        Update the value of a variable in a database
        """
        # init some shortcut
        variableId = str(variableId)

        # find variable by id
        sql = """SELECT * FROM `%s` WHERE  id=?""" % (self.tb_variables)
        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        columnName=True,
                                                        arg1=variableId)
        if not success:
            self.error("unable to read variable id")
            return (self.context.CODE_ERROR, "unable to read variable id")
        if not len(dbRows):
            return (self.context.CODE_NOT_FOUND,
                    "this variable id does not exist")

        sql_values = []
        sql_args = ()
        if variableName is not None:
            sql_values.append("""name=?""")
            sql_args += (variableName.upper(), )
        if variableValue is not None:
            # good json ?
            try:
                json.loads(variableValue)
            except Exception:
                return (self.context.CODE_ERROR, "bad json value provided")

            sql_values.append("""value=?""")
            sql_args += (variableValue, )
        if projectId is not None:
            projectId = str(projectId)
            sql_values.append("""project_id=?""")
            sql_args += (projectId, )

        # update
        if len(sql_values):
            sql_args += (variableId, )
            sql = """UPDATE `%s` SET %s WHERE id=?""" % (self.tb_variables,
                                                         ','.join(sql_values))
            success, _ = DbManager.instance().querySQL(query=sql,
                                                       args=sql_args)
            if not success:
                self.error("unable to update variable")
                return (self.context.CODE_ERROR, "unable to update variable")

        # new in v19, refresh the cache
        self.loadCacheVars()

        # refresh the context of all connected users
        self.context.refreshTestEnvironment()

        return (self.context.CODE_OK, "")
Beispiel #3
0
    def delProjectFromDB(self, projectId):
        """
        Delete a project from DB and disk
        """
        # init some shortcut
        projectId = str(projectId)

        # not possible to delete default project common
        if int(projectId) == 1:
            self.error("delete the default project not authorized")
            return (self.context.CODE_ERROR,
                    "delete the default project not authorized")

        # find the project id
        sql = """SELECT * FROM `%s` WHERE  id=?""" % (self.tb_projects)
        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        arg1=projectId)
        if not success:
            self.error("unable to read project id")
            return (self.context.CODE_ERROR, "unable to read project id")
        if not len(dbRows):
            return (self.context.CODE_NOT_FOUND,
                    "this project id does not exist")

        # checking relations projects`
        sql = """SELECT COUNT(*) as nbrelation FROM `relations-projects` WHERE  project_id=?"""
        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        columnName=True,
                                                        arg1=projectId)
        if not success:
            self.error("unable to read project relations")
            return (self.context.CODE_ERROR,
                    "unable to read project relations")
        if dbRows[0]["nbrelation"]:
            msg = "unable to remove project because linked to user(s)=%s" % dbRows[
                0]["nbrelation"]
            return (self.context.CODE_ERROR, msg)

        # delete from db
        sql = """DELETE FROM `%s` WHERE  id=?""" % (self.tb_projects)
        success, _ = DbManager.instance().querySQL(query=sql, arg1=projectId)
        if not success:
            self.error("unable to remove project by id")
            return (self.context.CODE_ERROR, "unable to remove project by id")

        # delete the folder according to the id of the project
        deleted = self.delProject(prjId=int(projectId))
        if not deleted:
            self.error("unable to delete project")
            # todo, cancel the previous delete
            return (self.context.CODE_ERROR, "unable to delete project")

        # refresh the cache, new in v19
        self.loadCache()

        return (self.context.CODE_OK, "")
Beispiel #4
0
    def updateProjectFromDB(self, projectName, projectId):
        """
        """
        # init some shortcut
        projectId = str(projectId)

        # not possible to delete default project common
        if int(projectId) == 1:
            self.error("update the default project not authorized")
            return (self.context.CODE_ERROR,
                    "update the default project is not authorized")

        if not len(projectName):
            self.error("project name is empty")
            return (self.context.CODE_ERROR, "the project name is empty")

        # find the project id
        sql = """SELECT * FROM `%s` WHERE  id=?""" % (self.tb_projects)
        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        arg1=projectId)
        if not success:
            self.error("unable to read project id")
            return (self.context.CODE_ERROR, "unable to read project id")
        if not len(dbRows):
            return (self.context.CODE_NOT_FOUND,
                    "this project id does not exist")

        # check if the name of the project already exists
        sql = """SELECT * FROM `%s` WHERE  name=?""" % (self.tb_projects)
        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        arg1=projectName)
        if not success:
            self.error("unable to read project's table")
            return (self.context.CODE_ERROR, "unable to read project's table")
        if len(dbRows):
            return (self.context.CODE_ALREADY_EXISTS,
                    "this name already exists")

        # update in db
        sql = """UPDATE `%s` SET name=? WHERE id=?""" % (self.tb_projects)
        success, _ = DbManager.instance().querySQL(query=sql,
                                                   arg1=projectName,
                                                   arg2=projectId)
        if not success:
            self.error("unable to update project by id")
            return (self.context.CODE_ERROR, "unable to update project by id")

        # refresh the cache, new in v19
        self.loadCache()

        return (self.context.CODE_OK, "")
Beispiel #5
0
    def addVariableInDB(self, projectId, variableName, variableValue):
        """
        Add a variable in the database
        """
        # init some shortcut
        projectId = str(projectId)

        if ":" in variableName:
            return (self.context.CODE_ERROR, "bad variable name provided")

        # check if the name is not already used
        sql = """SELECT * FROM `%s` WHERE name=?""" % (self.tb_variables)
        sql += """ AND project_id=?"""
        success, dbRows = DbManager.instance().querySQL(
            query=sql,
            columnName=True,
            arg1=variableName.upper(),
            arg2=projectId)
        if not success:
            self.error("unable to get variable by name")
            return (self.context.CODE_ERROR, "unable to get variable by name")
        if len(dbRows):
            return (self.context.CODE_ALREADY_EXISTS,
                    "this variable (%s) already exists" % variableName)

        # good json ?
        try:
            json.loads(variableValue)
        except Exception:
            return (self.context.CODE_ERROR, "bad json value provided")

        # this name is free then create project
        sql = """INSERT INTO `%s`(`name`, `value`, `project_id`)""" % self.tb_variables
        sql += """VALUES(?, ?, ?)"""
        success, lastRowId = DbManager.instance().querySQL(
            query=sql,
            insertData=True,
            arg1=variableName.upper(),
            arg2=variableValue,
            arg3=projectId)
        if not success:
            self.error("unable to insert variable")
            return (self.context.CODE_ERROR, "unable to insert variable")

        # new in v19, refresh the cache
        self.loadCacheVars()

        # refresh the context of all connected users
        self.context.refreshTestEnvironment()

        return (self.context.CODE_OK, "%s" % int(lastRowId))
    def resetPwdUserInDB(self, userId):
        """
        Reset a password in database
        """
        self.trace('Reset user`\'s password in database Id=%s' % userId)
        sql_args = ()

        # init some shortcut
        userId = str(userId)

        # find user by id
        sql = """SELECT * FROM `%s` WHERE  id=?""" % (self.tb_users)
        sql_args += (userId, )
        success, res = DbManager.instance().querySQL(query=sql,
                                                     columnName=True,
                                                     args=sql_args)
        if not success:
            self.error("unable to read user id")
            return (self.context.CODE_ERROR, "unable to read user id")
        if not len(res):
            return (self.context.CODE_NOT_FOUND, "this user id does not exist")

        # disconnect user before
        # todo

        # update password
        emptypwd = hashlib.sha1()
        emptypwd.update(''.encode("utf8"))
        sha1 = hashlib.sha1()
        pwd_salt = "%s%s" % (self.context.cfg_db["auth-salt"],
                             emptypwd.hexdigest())
        if sys.version_info < (3, ):
            sha1.update(pwd_salt)
        else:
            sha1.update(pwd_salt.encode('utf-8'))

        sql_args = ()
        sql = """UPDATE `%s` SET password=? WHERE id=?""" % (self.tb_users)
        sql_args += (sha1.hexdigest(), )
        sql_args += (userId, )
        success, _ = DbManager.instance().querySQL(query=sql, args=sql_args)
        if not success:
            self.error("unable to reset pwd")
            return (self.context.CODE_ERROR, "unable to reset pwd")

        # new in v19, refresh the cache
        self.loadCache()

        return (self.context.CODE_OK, "")
Beispiel #7
0
    def duplicateVariableInDB(self, variableId, projectId=None):
        """
        Duplicate a variable in database
        """
        # init some shortcut
        variableId = str(variableId)
        sql_args = ()

        # find variable by id
        sql = """SELECT * FROM `%s` WHERE  id=?""" % (self.tb_variables)
        sql_args += (variableId, )
        if projectId is not None:
            projectId = str(projectId)
            sql += """ AND project_id=?"""
            sql_args += (projectId, )

        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        columnName=True,
                                                        args=sql_args)
        if not success:
            self.error("unable to read variable id")
            return (self.context.CODE_ERROR, "unable to read variable id")
        if not len(dbRows):
            return (self.context.CODE_NOT_FOUND,
                    "this variable id does not exist")
        variable = dbRows[0]

        # duplicate variable
        newVarName = "%s-COPY#%s" % (variable['name'], uniqid())

        return self.addVariableInDB(projectId=variable["project_id"],
                                    variableName=newVarName,
                                    variableValue=variable["value"])
Beispiel #8
0
    def getVariablesFromDB(self, projectId=None):
        """
        Get test variables from database
        """
        sql_args = ()

        # get all users
        sql = """SELECT id, name, project_id"""
        sql += """, value"""
        sql += """ FROM `%s`""" % (self.tb_variables)
        if projectId is not None:
            projectId = str(projectId)
            sql += """ WHERE project_id=?"""
            sql_args += (projectId, )
        sql += """ ORDER BY name"""
        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        columnName=True,
                                                        args=sql_args)
        if not success:
            self.error("unable to read test environment table")
            return (self.context.CODE_ERROR,
                    "unable to test environment table")

        # new in v17 convert as json the result
        for d in dbRows:
            try:
                d['value'] = json.loads(d['value'])
            except Exception:
                d['value'] = "Bad JSON"
        # end of new

        return (self.context.CODE_OK, dbRows)
    def getUserFromDB(self, userId=None, userLogin=None):
        """
        Get user from database according to the id or login name
        """
        sql_args = ()

        # init some shortcut
        userId = str(userId)

        # get all users
        sql = """SELECT * FROM `%s`""" % (self.tb_users)
        sql += """ WHERE """
        if userId is not None:
            sql += """id=?"""
            sql_args += (userId, )
        if userLogin is not None:
            sql += """login LIKE ?"""
            sql_args += ("%%%s%%" % userLogin, )
        success, res = DbManager.instance().querySQL(query=sql,
                                                     columnName=True,
                                                     args=sql_args)
        if not success:
            self.error("unable to find user")
            return (self.context.CODE_ERROR, "unable to find user")

        return (self.context.CODE_OK, res[0])
Beispiel #10
0
    def delVariableInDB(self, variableId, projectId=None):
        """
        Delete a variable in database
        """
        # init some shortcut
        variableId = str(variableId)
        sql_args = ()

        # check if the name is not already used
        sql = """SELECT * FROM `%s` WHERE id=?""" % (self.tb_variables)
        sql_args += (variableId, )
        if projectId is not None:
            projectId = str(projectId)
            sql += """ AND project_id=?"""
            sql_args += (projectId, )

        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        columnName=True,
                                                        args=sql_args)
        if not success:
            self.error("unable to get variable by id")
            return (self.context.CODE_ERROR, "unable to get variable by id")
        if not len(dbRows):
            return (self.context.CODE_NOT_FOUND,
                    "variable id provided does not exist")

        # delete from db
        sql_args = ()
        sql = """DELETE FROM `%s` WHERE  id=?""" % (self.tb_variables)
        sql_args += (variableId, )
        if projectId is not None:
            projectId = str(projectId)
            sql += """ AND project_id=?"""
            sql_args += (projectId, )

        success, _ = DbManager.instance().querySQL(query=sql, args=sql_args)
        if not success:
            self.error("unable to remove variable by id")
            return (self.context.CODE_ERROR, "unable to remove variable by id")

        # new in v19, refresh the cache
        self.loadCacheVars()

        # refresh the context of all connected users
        self.context.refreshTestEnvironment()

        return (self.context.CODE_OK, "")
Beispiel #11
0
 def load_cache(self):
     """load cache"""
     self.cache = {}
     
     sql = """SELECT * FROM `%s`""" % (self.tb_agents)
     success, rows = DbManager.instance().querySQL(query=sql,
                                                   columnName=True)
     if not success:
         raise Exception("unable to init agents caching")
     
     for r in rows:
         self.cache[r["token"]] = r
Beispiel #12
0
    def getProjectsFromDB(self):
        """
        Delete all projects
        """
        # get all projects
        sql = """SELECT * FROM `%s`""" % (self.tb_projects)
        success, dbRows = DbManager.instance().querySQL(query=sql, columnName=True)
        if not success:
            self.error("unable to read project's table")
            return (self.context.CODE_ERROR, [])

        return (self.context.CODE_OK, dbRows)
Beispiel #13
0
    def addProjectToDB(self, projectName):
        """
        """
        if not len(projectName):
            self.error("project name is empty")
            return (self.context.CODE_ERROR, "project name is empty")

        # check if the name of the project already exists
        sql = """SELECT * FROM `%s` WHERE  name=?""" % (self.tb_projects)
        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        arg1=projectName)
        if not success:
            self.error("unable to read project's table")
            return (self.context.CODE_ERROR, "unable to read project's table")
        if len(dbRows):
            return (self.context.CODE_ALREADY_EXISTS,
                    "this name (%s) already exists" % projectName)

        # insert in db
        sql = """INSERT INTO `%s`(`name`, `active`) VALUES(?, '1')""" % (
            self.tb_projects)
        success, lastRowId = DbManager.instance().querySQL(query=sql,
                                                           insertData=True,
                                                           arg1=projectName)
        if not success:
            self.error("unable to insert project")
            return (self.context.CODE_ERROR, "unable to insert project")

        # create the folder according to the id of the project
        added = self.addProject(prjId=int(lastRowId))
        if not added:
            self.error("unable to add project")
            # todo, cancel the previous insert
            return (self.context.CODE_ERROR, "unable to add project")

        # refresh the cache, new in v19
        self.loadCache()

        return (self.context.CODE_OK, "%s" % int(lastRowId))
    def delUserInDB(self, userId):
        """
        Delete a user from database
        """
        self.trace('Delete user from database Id=%s' % userId)

        # init some shortcut
        userId = str(userId)

        # find user by id
        sql = """SELECT * FROM `%s` WHERE  id=?""" % (self.tb_users)
        success, res = DbManager.instance().querySQL(query=sql,
                                                     columnName=True,
                                                     arg1=userId)
        if not success:
            self.error("unable to read user id")
            return (self.context.CODE_ERROR, "unable to read user id")
        if not len(res):
            return (self.context.CODE_NOT_FOUND, "this user id does not exist")

        # delete from db
        sql = """DELETE FROM `%s` WHERE  id=?""" % (self.tb_users)
        success, res = DbManager.instance().querySQL(query=sql, arg1=userId)
        if not success:
            self.error("unable to remove user by id")
            return (self.context.CODE_ERROR, "unable to remove user by id")

        # delete relations from db
        sql = """DELETE FROM `relations-projects` WHERE  user_id=?"""
        success, res = DbManager.instance().querySQL(query=sql, arg1=userId)
        if not success:
            self.error("unable to remove user relation")
            return (self.context.CODE_ERROR, "unable to remove user relation")

        # new in v19, refresh the cache
        self.loadCache()

        return (self.context.CODE_OK, "")
    def getRelationsFromDB(self):
        """
        Get all relations from database
        """
        self.trace('Get all relations from database')

        # get all users
        sql = """SELECT * FROM `relations-projects`"""
        success, res = DbManager.instance().querySQL(query=sql, columnName=True)
        if not success:
            self.error("unable to read relation's table")
            return (self.context.CODE_ERROR, "unable to read relation's table")

        return (self.context.CODE_OK, res)
    def updateStatusUserInDB(self, userId, status):
        """
        Enable or disable a user in database
        """
        self.trace('Enable/disable user in database Id=%s' % userId)
        sql_args = ()

        # init some shortcut
        userId = str(userId)

        # find user by id
        sql = """SELECT * FROM `%s` WHERE  id=?""" % (self.tb_users)
        sql_args += (userId, )
        success, res = DbManager.instance().querySQL(query=sql,
                                                     columnName=True,
                                                     args=sql_args)
        if not success:
            self.error("unable to read user id")
            return (self.context.CODE_ERROR, "unable to read user id")
        if not len(res):
            return (self.context.CODE_NOT_FOUND, "this user id does not exist")

        # update
        sql_args = ()
        sql = """UPDATE `%s` SET active=? WHERE id=?""" % (self.tb_users)
        sql_args += (int(status), )
        sql_args += (userId, )
        success, _ = DbManager.instance().querySQL(query=sql, args=sql_args)
        if not success:
            self.error("unable to change the status of the user")
            return (self.context.CODE_ERROR,
                    "unable to change the status of the user")

        # new in v19, refresh the cache
        self.loadCache()

        return (self.context.CODE_OK, "")
    def getUsersFromDB(self):
        """
        Get all users from database
        Returns all users, except the first one (system)
        """
        self.trace('Get all users from database')

        # get all users
        sql = """SELECT * FROM `%s`""" % (self.tb_users)
        success, res = DbManager.instance().querySQL(query=sql, columnName=True)
        if not success:
            self.error("unable to read user's table")
            return (self.context.CODE_ERROR, "unable to read user's table")

        return (self.context.CODE_OK, res)
    def readConfigDb(self):
        """
        """
        self.trace("Loading config from database in memory")

        sql = """SELECT * FROM `config`"""
        success, res = DbManager.instance().querySQL(query=sql,
                                                     columnName=True)
        if not success:
            raise Exception("unable to read config from database")

        # populate cfg variable
        for line in res:
            self.cfg_db[line["opt"]] = line["value"]

        del res
    def setOnlineStatus(self, login, online):
        """
        Set the online status of a specific user
        """
        self.trace('Set online status User=%s' % login)

        sql_args = ()
        sql = "UPDATE `%s` SET online=? WHERE login=?" % (self.tb_users)
        sql_args += (int(online), )
        sql_args += (login, )
        success, _ = DbManager.instance().querySQL(query=sql, args=sql_args)
        if not success:
            self.error("unable to update online status user=%s value=%s" %
                       (login, online))

        # new in v19, refresh the users cache
        self.loadCache()
    def duplicateUserInDB(self, userId):
        """
        Duplicate a user in database
        """
        self.trace('Duplicate user from database Id=%s' % userId)

        # init some shortcut
        userId = str(userId)

        # find user by id
        sql_args = ()
        sql = """SELECT * FROM `%s` WHERE  id=?""" % (self.tb_users)
        sql_args += (userId, )
        success, res = DbManager.instance().querySQL(query=sql,
                                                     columnName=True,
                                                     args=sql_args)
        if not success:
            self.error("unable to read user id")
            return (self.context.CODE_ERROR, "unable to read user id")
        if not len(res):
            return (self.context.CODE_NOT_FOUND, "this user id does not exist")
        user = res[0]

        # duplicate user
        newLogin = "******" % (user['login'], uniqid())
        level = "tester"
        if user['administrator']:
            level = "administrator"
        if user['monitor']:
            level = "monitor"
        if user['tester']:
            level = "tester"
        return self.addUserToDB(login=newLogin,
                                password='',
                                email=user['email'],
                                level=level,
                                lang=user['lang'],
                                style=user['style'],
                                notifications=user['notifications'],
                                defaultPrj=user['defaultproject'],
                                listPrjs=[user['defaultproject']])
Beispiel #21
0
    def getProjectFromDB(self, projectName=None, projectId=None):
        """
        """
        sql_args = ()

        # get all projects
        sql = """SELECT * FROM `%s`""" % (self.tb_projects)
        sql += """ WHERE """
        if projectName is not None:
            sql += """name LIKE ?"""
            sql_args += ("%%%s%%" % projectName, )
        if projectId is not None:
            sql += """ id=?"""
            sql_args += (projectId, )
        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        columnName=True,
                                                        args=sql_args)
        if not success:
            self.error("unable to search project table")
            return (self.context.CODE_ERROR, "unable to search project table")

        return (self.context.CODE_OK, dbRows)
Beispiel #22
0
    def delVariablesInDB(self, projectId):
        """
        Delete all variables in database
        """
        # init some shortcut
        projectId = str(projectId)
        sql_args = ()

        # delete from db
        sql = """DELETE FROM `%s` WHERE  project_id=?""" % (self.tb_variables)
        sql_args += (projectId, )
        success, _ = DbManager.instance().querySQL(query=sql, args=sql_args)
        if not success:
            self.error("unable to reset variables")
            return (self.context.CODE_ERROR, "unable to reset variables")

        # new in v19, refresh the cache
        self.loadCacheVars()

        # refresh the context of all connected users
        self.context.refreshTestEnvironment()

        return (self.context.CODE_OK, "")
Beispiel #23
0
    def getVariableFromDB(self, projectId, variableName=None, variableId=None):
        """
        Get a specific variable from database
        """
        # init some shortcut
        projectId = str(projectId)
        sql_args = ()

        # get all users
        sql = """SELECT id, name, project_id"""
        sql += """, value"""
        sql += """ FROM `%s`""" % (self.tb_variables)
        sql += """ WHERE project_id=?"""
        sql_args += (projectId, )
        if variableName is not None:
            sql += """ AND name LIKE ?"""
            sql_args += ("%%%s%%" % variableName, )
        if variableId is not None:
            variableId = str(variableId)
            sql += """ AND id=?"""
            sql_args += (variableId, )
        success, dbRows = DbManager.instance().querySQL(query=sql,
                                                        columnName=True,
                                                        args=sql_args)
        if not success:
            self.error("unable to search test environment table")
            return (self.context.CODE_ERROR,
                    "unable to search variable in test environment table")

        # new in v17 convert as json the result
        for d in dbRows:
            try:
                d['value'] = json.loads(d['value'])
            except Exception:
                d['value'] = "Bad JSON"
        # end of new
        return (self.context.CODE_OK, dbRows)
    def cleanup(self):
        """
        Cleanup the server
        """
        self.info('Cleanup...')

        self.trace("Cleanup agent manager")
        try:
            AgentsManager.finalize()
        except Exception:
            pass

        self.trace("Cleanup context")
        try:
            Context.finalize()
        except Exception:
            pass

        self.trace("Cleanup projects manager")
        try:
            ProjectsManager.finalize()
        except Exception:
            pass

        self.trace("Cleanup users manager")
        try:
            UsersManager.finalize()
        except Exception:
            pass

        self.trace("Cleanup task manager")
        try:
            TaskManager.finalize()
        except Exception:
            pass

        self.trace("Cleanup test public manager")
        try:
            RepoPublic.finalize()
        except Exception:
            pass

        self.trace("Cleanup test repo manager")
        try:
            RepoTests.finalize()
        except Exception:
            pass

        self.trace("Cleanup test archives manager")
        try:
            RepoArchives.finalize()
        except Exception:
            pass

        self.trace("Cleanup helper manager")
        try:
            HelperManager.finalize()
        except Exception:
            pass

        self.trace("Cleanup adapters manager")
        try:
            RepoAdapters.finalize()
        except Exception:
            pass

        self.trace("Cleanup adapters data storage")
        try:
            StorageDataAdapters.finalize()
        except Exception:
            pass

        self.trace("Cleanup WSU")
        try:
            RestServerInterface.instance().stop()
            RestServerInterface.finalize()
        except Exception:
            pass

        self.trace("Cleanup ESI")
        try:
            EventServerInterface.instance().stopSA()
            EventServerInterface.finalize()
        except Exception:
            pass

        self.trace("Cleanup TSI")
        try:
            TestServerInterface.instance().stopSA()
            TestServerInterface.finalize()
        except Exception:
            pass

        self.trace("Cleanup ASI")
        try:
            AgentServerInterface.instance().stopSA()
            AgentServerInterface.finalize()
        except Exception:
            pass

        self.trace("Cleanup db manager")
        try:
            DbManager.finalize()
        except Exception:
            pass

        self.trace("Cleanup settings")
        try:
            Settings.finalize()
        except Exception:
            pass

        self.trace("Cleanup logger, cli")
        try:
            CliFunctions.finalize()
            Logger.finalize()
        except Exception:
            pass
    def updatePwdUserInDB(self, userId, newPwd, curPwd):
        """
        Update password's user in database
        """
        self.trace('Update user\'s password in database Id=%s' % userId)

        sql_args = ()

        # init some shortcut
        userId = str(userId)

        # find user by id
        sql = """SELECT * FROM `%s` WHERE  id=?""" % (self.tb_users)
        sql_args += (userId, )
        success, res = DbManager.instance().querySQL(query=sql,
                                                     columnName=True,
                                                     args=sql_args)
        if not success:
            self.error("unable to find user id")
            return (self.context.CODE_ERROR, "unable to find user id")
        if not len(res):
            return (self.context.CODE_NOT_FOUND, "this user id does not exist")

        # current password
        sha1_cur = hashlib.sha1()
        sha1_cur.update(curPwd.encode("utf8"))

        sha1_cur2 = hashlib.sha1()
        pwd1_salt2 = "%s%s" % (self.context.cfg_db["auth-salt"],
                               sha1_cur.hexdigest())
        if sys.version_info < (3, ):
            sha1_cur2.update(pwd1_salt2)
        else:
            sha1_cur2.update(pwd1_salt2.encode('utf-8'))

        if sha1_cur2.hexdigest() != res[0]['password']:
            return (self.context.CODE_FORBIDDEN,
                    "Bad current password provided")

        # update password
        sha1_new = hashlib.sha1()
        sha1_new.update(newPwd.encode("utf8"))

        sha1_new2 = hashlib.sha1()
        pwd_salt2 = "%s%s" % (self.context.cfg_db["auth-salt"],
                              sha1_new.hexdigest())
        if sys.version_info < (3, ):
            sha1_new2.update(pwd_salt2)
        else:
            sha1_new2.update(pwd_salt2.encode('utf-8'))

        sql_args = ()
        sql = """UPDATE `%s` SET password=? WHERE id=?""" % (self.tb_users)
        sql_args += (sha1_new2.hexdigest(), )
        sql_args += (userId, )
        success, _ = DbManager.instance().querySQL(query=sql, args=sql_args)
        if not success:
            self.error("unable to update pwd")
            return (self.context.CODE_ERROR, "unable to update pwd")

        # new in v19, refresh the cache
        self.loadCache()

        return (self.context.CODE_OK, "")
    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
        userId = str(userId)

        # search  user by id
        sql = """SELECT * FROM `%s` WHERE  id=?""" % (self.tb_users)
        success, _ = DbManager.instance().querySQL(query=sql,
                                                   columnName=True,
                                                   arg1=userId)
        if not success:
            self.error("unable to search user by id")
            return (self.context.CODE_ERROR, "unable to read user id")

        sql_values = []
        sql_args = ()
        if login is not None:
            # check if this new login if available ?
            sql = """SELECT * FROM `%s` WHERE  login=? AND id != ?""" % (
                self.tb_users)
            success, res = DbManager.instance().querySQL(query=sql,
                                                         columnName=True,
                                                         arg1=login,
                                                         arg2=userId)
            if not success:
                self.error("unable to search user login")
                return (self.context.CODE_ERROR, "unable to read user id")
            if len(res):
                return (self.context.CODE_ALREADY_EXISTS,
                        "This login already exist")
            else:
                sql_values.append("""login=?""")
                sql_args += (login, )
        if email is not None:
            sql_values.append("""email=?""")
            sql_args += (email, )
        if lang is not None:
            sql_values.append("""lang=?""")
            sql_args += (lang, )
        if style is not None:
            sql_values.append("""style=?""")
            sql_args += (style, )
        if notifications is not None:
            sql_values.append("""notifications=?""")
            sql_args += (notifications, )
        if default is not None:
            default = str(default)
            sql_values.append("""defaultproject=?""")
            sql_args += (default, )

        # access level
        if level is not None:
            if level == "administrator":
                sql_values.append("""administrator='1'""")
                sql_values.append("""monitor='0'""")
                sql_values.append("""tester='0'""")
            elif level == "monitor":
                sql_values.append("""administrator='0'""")
                sql_values.append("""monitor='1'""")
                sql_values.append("""tester='0'""")
            else:
                sql_values.append("""administrator='0'""")
                sql_values.append("""monitor='0'""")
                sql_values.append("""tester='1'""")

        # update
        if len(sql_values):
            sql_args += (userId, )
            sql = """UPDATE `%s` SET %s WHERE id=?""" % (self.tb_users,
                                                         ','.join(sql_values))
            success, _ = DbManager.instance().querySQL(query=sql,
                                                       args=sql_args)
            if not success:
                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 `relations-projects` WHERE user_id=?"""
            success, _ = DbManager.instance().querySQL(query=sql, arg1=userId)
            if not success:
                self.error("unable to delete relations")
                return (self.context.CODE_ERROR, "unable to delete relations")

            # adding relations-projects`
            sql = """INSERT INTO `relations-projects`(`user_id`, `project_id`) VALUES"""
            sql_values = []
            sql_args = ()
            for prj in projects:
                prj = int(prj)
                sql_values.append("""(?, ?)""")
                sql_args += (
                    userId,
                    prj,
                )

            sql += ', '.join(sql_values)
            success, _ = DbManager.instance().querySQL(query=sql,
                                                       insertData=True,
                                                       args=sql_args)
            if not success:
                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, "")
    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)

        # find user by name
        sql = """SELECT * FROM `%s` WHERE login=?""" % (self.tb_users)
        success, res = DbManager.instance().querySQL(query=sql,
                                                     columnName=True,
                                                     arg1=login)
        if not success:
            self.error("unable to read user by name")
            return (self.context.CODE_ERROR, "unable to read user by name")
        if len(res):
            return (self.context.CODE_ALREADY_EXISTS,
                    "this user name already exists")

        self.trace(level)
        admin = 0
        monitor = 0
        tester = 0
        # access level
        if level == "administrator":
            admin = 1
        elif level == "monitor":
            monitor = 1
        else:
            tester = 1
        self.trace("%s %s %s" % (admin, monitor, tester))

        #  password, create a sha1 hash with salt: sha1(salt + sha1(password))
        sha1_pwd = hashlib.sha1()
        sha1_pwd.update(password.encode("utf8"))

        sha1 = hashlib.sha1()
        pwd_salt = "%s%s" % (self.context.cfg_db["auth-salt"],
                             sha1_pwd.hexdigest())
        if sys.version_info < (3, ):
            sha1.update(pwd_salt)
        else:
            sha1.update(pwd_salt.encode('utf-8'))

        # create random apikey
        apikey_secret = hexlify(os.urandom(20))
        if sys.version_info > (3, ):
            apikey_secret = apikey_secret.decode("utf8")

        # prepare the sql query
        sql = """INSERT INTO `%s`(`login`, `password`, `administrator`, """ % self.tb_users
        sql += """`monitor`, `tester`, `email`, `lang`, """
        sql += """`style`, `active`, `online`, `notifications`, """
        sql += """`defaultproject`, `apikey_id`, `apikey_secret`)"""
        sql += """ VALUES(?, ?, ?, """
        sql += """?, ?, ?, ?,"""
        sql += """?, '1', '0', ?, """
        sql += """?, ?, ?)"""
        success, lastRowId = DbManager.instance().querySQL(
            query=sql,
            insertData=True,
            arg1=login,
            arg2=sha1.hexdigest(),
            arg3=admin,
            arg4=monitor,
            arg5=tester,
            arg6=email,
            arg7=lang,
            arg8=style,
            arg9=notifications,
            arg10=defaultPrj,
            arg11=login,
            arg12=apikey_secret)
        if not success:
            self.error("unable to insert user")
            return (self.context.CODE_ERROR, "unable to insert user")

        # adding relations-projects`
        sql_args = ()
        sql = """INSERT INTO `relations-projects`(`user_id`, `project_id`) VALUES"""
        sql_values = []
        try:
            for prj in listPrjs:
                prj = int(prj)
                sql_values.append("""(?, ?)""")
                sql_args += (
                    lastRowId,
                    prj,
                )
        except Exception:
            return (self.context.CODE_ERROR, "bad project list provided")

        sql += ', '.join(sql_values)
        success, _ = DbManager.instance().querySQL(query=sql,
                                                   insertData=True,
                                                   args=sql_args)
        if not success:
            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))
    def initialize(self):
        """
        Starts all modules
        Exit if the service is alreayd running or if the config file is missing
        """
        starttime = time.time()
        if self.isrunning():
            sys.stdout.write(" (server is already running)")
            sys.exit(1)

        # run the server as daemon only for linux
        if platform.system() == "Linux":
            self.daemonize()

        try:
            # Initialize
            self.info("Starting up server...")
            self.trace("** System encoding (in): %s" % sys.stdin.encoding)
            self.trace("** System encoding (out): %s" % sys.stdout.encoding)
            self.info("Settings, Logger and CLI ready")

            DbManager.initialize()
            DbManager.instance().isUp()
            self.info("Database manager ready")

            # Initialize the core
            Context.initialize()
            self.info("Context ready")

            ProjectsManager.initialize(context=Context.instance())
            self.info("Projects Manager ready")
            UsersManager.initialize(context=Context.instance())
            self.info("Users Manager ready")

            TaskManager.initialize(context=Context)
            self.info("Task Manager ready")

            # Initialize all repositories
            RepoTests.initialize(context=Context.instance())
            self.info("Repo manager for tests ready")
            RepoArchives.initialize(context=Context.instance())
            self.info("Repo manager for archives ready")
            RepoAdapters.initialize(context=Context.instance())
            StorageDataAdapters.initialize(context=Context.instance())
            self.info("Adapters Manager and Storage Data ready")
            RepoPublic.initialize()
            self.info("Repo manager for public area is ready")

            HelperManager.initialize()
            self.info("Helper manager ready")

            AgentsManager.initialize(context=Context.instance())
            self.info("Agents Manager ready")

            # Initialize all interfaces
            self.info("Starting ESI on %s:%s" % (Settings.get('Bind', 'ip-esi'),
                                                 Settings.getInt('Bind', 'port-esi')))
            EventServerInterface.initialize(listeningAddress=(Settings.get('Bind', 'ip-esi'),
                                                              Settings.getInt(
                'Bind', 'port-esi')
            ),
                sslSupport=Settings.getInt(
                'Client_Channel', 'channel-ssl'),
                wsSupport=Settings.getInt(
                'Client_Channel', 'channel-websocket-support'),
                context=Context.instance()
            )
            self.info("Starting TSI on %s:%s" % (Settings.get('Bind', 'ip-tsi'),
                                                 Settings.getInt('Bind', 'port-tsi')))
            TestServerInterface.initialize(listeningAddress=(Settings.get('Bind', 'ip-tsi'),
                                                             Settings.getInt(
                                                                 'Bind', 'port-tsi')
                                                             ),
                                           context=Context.instance()
                                           )
            self.info("Starting RSU on %s:%s" % (Settings.get('Bind', 'ip-rsi'),
                                                 Settings.getInt('Bind', 'port-rsi')))
            RestServerInterface.initialize(listeningAddress=(Settings.get('Bind', 'ip-rsi'),
                                                             Settings.getInt(
                'Bind', 'port-rsi')
            )
            )
            self.info("Starting ASI on %s:%s" % (Settings.get('Bind', 'ip-asi'),
                                                 Settings.getInt('Bind', 'port-asi')))
            AgentServerInterface.initialize(listeningAddress=(Settings.get('Bind', 'ip-asi'),
                                                              Settings.getInt(
                'Bind', 'port-asi')
            ),
                sslSupport=Settings.getInt(
                'Agent_Channel', 'channel-ssl'),
                wsSupport=Settings.getInt(
                'Agent_Channel', 'channel-websocket-support'),
                tsi=TestServerInterface.instance(),
                context=Context.instance()
            )

            # Start on modules
            RestServerInterface.instance().start()
            self.info("RSI is listening on tcp://%s:%s" % (Settings.get('Bind', 'ip-rsi'),
                                                           Settings.get('Bind', 'port-rsi')))
            EventServerInterface.instance().startSA()
            self.info("ESI is listening on tcp://%s:%s" % (Settings.get('Bind', 'ip-esi'),
                                                           Settings.get('Bind', 'port-esi')))
            TestServerInterface.instance().startSA()
            self.info("TSI is listening on tcp://%s:%s" % (Settings.get('Bind', 'ip-tsi'),
                                                           Settings.get('Bind', 'port-tsi')))
            AgentServerInterface.instance().startSA()
            self.info("ASI is listening on tcp://%s:%s" % (Settings.get('Bind', 'ip-asi'),
                                                           Settings.get('Bind', 'port-asi')))

            # Now start the scheduler and reload tasks
            taskReloaded = TaskManager.instance().loadBackups()
            if taskReloaded is None:
                self.info("Reload tasks disabled")
            elif taskReloaded:
                self.info("Tasks reloaded")
            else:
                self.error("Failed to reload tasks")

        except Exception as e:
            self.error("Unable to start server: %s" % str(e))
            self.cleanup()
            sys.exit(3)

        stoptime = time.time()
        self.info("%s successfully started (in %s sec.)" % (Settings.get('Server', 'name'),
                                                            int(stoptime - starttime)))

        # only for windows platform
        if platform.system() == "Windows":
            print("Server successfully started...")

        self.setrunning()
        self.run()