Exemplo n.º 1
0
def run():
    logger, logFile, errorFile = Utils.loggerUtil()
    ctmvarCommand = ['ctmvar', '-action', 'list']
    neededVarExpr = ''
    try:
        splittedLines = commandExecuter.run(ctmvarCommand)
        if isinstance(splittedLines, list):
            splittedLines = splittedLines[5:-3]
            #varsTable = []
            isFound = False
            for line in splittedLines:
                try:
                    line = line.decode('ascii').split()
                    #varsTable.append(line)
                    if line:  # Check if the line is not empty
                        # Every line (which not empty includes the var name at the first field)
                        if settings.varName == line[0]:
                            isFound = True
                            logger.info("< {} > ".format(settings.varName) + "Found the following line : " + str(line))
                            neededVarExpr = line[1]
                            pass
                    else:
                        continue
                except Exception as e:
                    logger.warn("< {} > {} for line : \n {} ".format(settings.varName, e, line) )
                    sendMailNotification.run(logFile, errorFile)
                    continue
            if not isFound:
                raise Exception("Something went wrong! no matching found...Exiting with code 4!", 4, logger.name)
            else:
                return(neededVarExpr)
        else:
            raise Exception("Returned empty list from command : {}".format(ctmvarCommand), logger.name)
    except Exception as e:
        raise
def run(commandToExecute):
    logger, _, _ = Utils.loggerUtil()
    try:
        ctmpsmOutput = subp.Popen(commandToExecute,
                                  stdout=subp.PIPE,
                                  stderr=subp.PIPE,
                                  shell=True)
        out, err = ctmpsmOutput.communicate()
        splittedLines = out.splitlines()
        rc = ctmpsmOutput.returncode
        if rc != 0:
            errors = "\n".join(
                [str(x.decode('ascii')) for x in err.splitlines()])
            output = "\n".join(
                [str(x.decode('ascii')) for x in out.splitlines()])
            if errors:
                raise Exception(errors)
            if output:
                raise Exception(output)
            if errors and output:
                raise Exception(output + "\n" + errors)
        return splittedLines
    except Exception as e:
        raise Exception(
            "Something went wrong with the command : " +
            str(commandToExecute) + "\n" + str(e.args[0]) +
            "\nExiting with code  9!", 9, logger.name)
Exemplo n.º 3
0
def moveUnknownFiles(i_FullPath, i_FullUnknownPath):
    import glob
    logger, logFile, errorFile = Utils.loggerUtil()
    for file in glob.glob(i_FullPath + "*"):
        _, fileName = os.path.split(file)
        logger.warn("File {} still exists after run, moving to unknown folder".format(fileName))
        try:
            shutil.move(file, os.path.join(i_FullUnknownPath, fileName))
        except Exception as e:
            logger.error("< {}::{} > ".format(subDirName, fileName) + str(e), exc_info=True)
Exemplo n.º 4
0
def run():
    logger, _, _ = Utils.loggerUtil()
    logger.info("< {} > ".format(settings.varName) +
                "Going to Send ForceOK to OrderID : " + settings.orderID)
    ctmpsmUpdateCommand = ['ctmpsm', '-updateajf', settings.orderID, 'FORCEOK']
    try:
        splittedLines = commandExecuter.run(ctmpsmUpdateCommand)
        logger.info("< {} > ".format(settings.varName) +
                    "\n".join([str(x.decode('ascii')) for x in splittedLines]))
    except Exception as e:
        raise
Exemplo n.º 5
0
def main():
    settings.init()
    argv = sys.argv[2:]
    try:
        logger, logFile, errorFile = Utils.loggerUtil()
        numOfArgs = len(sys.argv)
        if numOfArgs <= 2:
            raise Exception("no arguments sent! check it!", 9, logger.name)
        currentFileName = os.path.basename(__file__)
        try:
            opts, args = getopt.getopt(argv, 'hv:', ["VarName="])
        except getopt.GetoptError as ge:
            raise Exception(ge.msg, 99, logger.name)
        if len(opts) == 0:
            raise Exception("No Var Name sent! \'-v\' flag should be used", 9,
                            logger.name)
        for opt, arg in opts:
            if opt == '-h':
                print(currentFileName + " -v VarName")
                sys.exit()
            elif opt in ("-v", "--VarName"):
                settings.varName = arg
                settings.varName = "%%" + settings.varName
            logger.info("< {} > ".format(settings.varName) +
                        "*****\t\tNew request - Var name is : " +
                        settings.varName)
        logger.info("< {} > ".format(settings.varName) +
                    "Going to search for var : " + settings.varName +
                    " in Global var list")
        settings.orderID = getNeededVarExpr.run()
        updateJob.run()
    except Exception as e:
        exception = e.args[0]
        returningFunction = e.args[2]
        logger.name = returningFunction
        logger.error("< {} > ".format(settings.varName) + exception,
                     exc_info=True)
        '''
        localLogger.name = returningFunction
        localLogger.error("< {} > ".format(varName) + exception, exc_info=True)
        '''
        #print(exception)
        # Send Mail notification for exceptions with log file attached
        sendMailNotification.run(logFile, errorFile)
        if len(e.args) > 1:
            exitCode = e.args[1]
            exit(exitCode)
        else:
            raise
            xmlLoc = '9ProdLinux.xml'
            envAskFlag = False
        elif env in ['Test', 'test', 'T', 't']:
            CTMServer = 'pctmtapp9'
            xmlLoc = '9TestLinux.xml'
            envAskFlag = False
        else:
            print("Wrong Selection!")
    xmlLoc = "FullInstallations/Agent/latest/Unix/" + xmlLoc
    linuxUserName = '******'
    linuxPassword = getpass.getpass("Enter Password For ctmuser : "******"Connections Established to host {}!".format(serverName))
        Main(linuxUserName, sshSession)
        sshSession.close()
        sshSession = Utils.linuxConnector(CTMServer, linuxUserName, linuxPassword)

    except Exception as e:
        exception = e.args[0]
        print(exception)
        if len(e.args) > 1 :
            exitCode = e.args[1]
            exit(exitCode)
        else:
            raise
    finally:
        if sshSession:
Exemplo n.º 7
0
def main():
    maxRC = 0
    argv = sys.argv[2:]
    today = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
    fileName = None
    subDirName = None
    logger,logFile, errorFile = Utils.loggerUtil()
    try:
        numOfArgs = len(sys.argv)
        if numOfArgs <= 1:
            raise Exception("no arguments sent! check it!", 9, logger.name)
        try:
            opts, args = getopt.getopt(argv, 'hf:d:e:', ["Help", "FileName=", "Dir=", "Env="])
        except getopt.GetoptError as ge:
            raise Exception(ge.msg, 99, logger.name)
        if len(opts) < 3:
            raise Exception("Missing parameters: -f | -n | -p", 9, logger.name)
        for opt, arg in opts:
            if opt == '-h':
                print(" -f FileName -d DirName -e Env")
                sys.exit()
            elif opt in ("-f", "--FileName"):
                fileName = arg
            elif opt in ("-d", "--Dir"):
                subDirName = arg
            elif opt in ("-e", "--Env"):
                env = arg

        logger.info("Got The following : File = {}, sub Dir = {}, Env = {}".format(fileName, subDirName, env))
        if env == "Test":
            sourcePath = r'\\ntsrv1\IVR_TEAM\gcti\DYN_Messages_Test\he-IL'
            numOfServers = 2
            serversPrefix = "stctimcp0"
        elif env == "Prod":
            sourcePath = r'\\ntsrv1\IVR_TEAM\gcti\DYN_Messages\he-IL'
            numOfServers = 6
            serversPrefix = "pctimcp0"
        else:
            raise Exception("Unknown environment specified : {}".format(env))
        destPath = r'D$\gcti\DYN_Messages\he-IL'
        destServersNum = list(range(1, numOfServers+1))
        destServersNum = list(map(str, destServersNum))
        dirsList = [
            "IVR_points",
            "Dynamic_Menus",
            "Special_Days",
            "DNIS_WelcomeMessages"
        ]
        baseFileName, fileExt = os.path.splitext(fileName)
        fileNameNoNum = baseFileName.split("_")[:-1]
        if not fileNameNoNum:
            raise Exception("Filename isn't In *_.* format!",9)
        fileNameNoNum = ''.join(map(str, fileNameNoNum))
        logger.info("The Files starting with {} will be proceed".format(fileNameNoNum))
        if subDirName in dirsList:
            for num in destServersNum:
                curFileName = fileNameNoNum + "_" + num + fileExt
                fullSourcePath = os.path.join(sourcePath, os.path.join(subDirName,curFileName))
                fullSourcePathNoNum = os.path.join(sourcePath, os.path.join(subDirName,fileNameNoNum))
                fullFailurePath = os.path.join(sourcePath, os.path.join(subDirName,
                                                                            os.path.join("failed", curFileName)))
                fullUnknownPath = os.path.join(sourcePath, os.path.join(subDirName, "unknown"))
                if os.path.exists(fullSourcePath):
                    backUpFileName = fileNameNoNum + "_" + num + "-" + str(today) + fileExt
                    fullBackUpPath = os.path.join(sourcePath, os.path.join(subDirName,
                                                                            os.path.join("backup", backUpFileName)))
                    fullDestPath = os.path.join(r"\\" + serversPrefix + num, os.path.join(destPath,
                                                                            os.path.join(subDirName, fileNameNoNum + fileExt)))
                    try:
                        shutil.copyfile(fullSourcePath, fullDestPath)
                        logger.info("File - {} copied successfully to {}".format(curFileName, fullDestPath))
                        logger.info("Going To backup the file to {}".format(fullBackUpPath))
                        shutil.move(fullSourcePath, fullBackUpPath)
                        logger.info("Backed Up.")
                    except Exception as e:
                        logger.error("< {}::{} > ".format(subDirName, fileName) + str(e), exc_info=True)
                        shutil.move(fullSourcePath, fullFailurePath)
                        if maxRC < 3: maxRC = 3
                        continue
                else:
                    logger.warn("File {} doesn't exist".format(curFileName))
                    if maxRC < 2: maxRC = 2
                    continue
            # Checking if there are still files starting with the prefix and moving them to unknown folder
            moveUnknownFiles(fullSourcePathNoNum, fullUnknownPath)
        else:
            raise Exception("Unknown Directory name provided: {}".format(subDirName), 9, logger.name)
    except Exception as e:
        exception = e.args[0]
        if e.args[2]:
            returningFunction = e.args[2]
            logger.name = returningFunction
        logger.error("< {}::{} > ".format(subDirName, fileName) + str(exception), exc_info=True)
        if len(e.args) > 1:
            exitCode = e.args[1]
            exit(exitCode)
        else:
            raise
    exit(maxRC)