Beispiel #1
0
def sendmail(subject, from_mail, to_mail, msg, html_msg=None):
    me = from_mail
    you = re.split(r'[;,\s]\s*', to_mail)

    # Create message container - the correct MIME type is multipart/alternative.
    mime = MIMEMultipart('alternative')
    mime['Subject'] = subject
    mime['From'] = me
    mime['To'] = to_mail

    if not html_msg:
        html_msg = "<html> <pre> " + msg + "</pre> </html>"

    part1 = MIMEText(msg, 'plain')
    part2 = MIMEText(html_msg, 'html')
    mime.attach(part1)
    mime.attach(part2)

    try:
        autopsy_logger.info("Sending mail to: " + to_mail)
        server = smtplib.SMTP('localhost')
        server.set_debuglevel(0)

        server.sendmail(me, you, mime.as_string())
        server.quit()
    except socket.error as e:
        autopsy_logger.error("Couldn't send mail, check your local SMTP client: " + str(e))
Beispiel #2
0
    def __init__(self, tbContent):
        self.tbname = None
        self.tbFileName = None
        self.userid = None
        self.tenantid = None
        self.emailid = None
        self.host = None

        self.no_download_logs = False
        self.__im1_lock = threading.RLock()

        autopsy_logger.info("Building testbed")
        if type(tbContent) is dict:
            self.parse_json(tbContent)
            self.tbFileName = self.tbname
        elif type(tbContent) is str:
            self.tbFileName = os.path.basename(tbContent)
            try:
                tbfile = open(tbContent)
            except IOError as e:
                autopsy_logger.critical(
                    "Testbed file doesn't exist: {0}".format(tbContent))
                raise TestbedNotFoundException(
                    "Testbed file doesn't exist: {0}".format(tbContent))
            try:
                self.parse_json(json.loads((tbfile.read())))
            except ValueError as e:
                autopsy_logger.critical(
                    "Testbed JSON file is not well formatted. Please check and try again"
                )
                raise e
Beispiel #3
0
def preConfig():
    if simulate_wan_type:
        autopsy_logger.info("Configuring wan type as : " + simulate_wan_type,
                            fg_color=AutopsyLogger.MAGENTA)

        host1.simulate_wan_characteristics("eth0", "add", wan_type=simulate_wan_type)
        host2.simulate_wan_characteristics("eth0", "add", wan_type=simulate_wan_type)
Beispiel #4
0
 def decorate(oldclass):
     if args[0]:
         autopsy_logger.info("Skipping '{0}' as {1}".format(oldclass.__name__, args[1] if len(args) > 1 and args[
             1] else "Skip Condition met"),
                             fg_color=autopsy_logger.MAGENTA)
         return autopsyskip(oldclass)
     return oldclass
Beispiel #5
0
    def sendmail(self, msg):
        if self.mailto is None or self.mailto == '':
            return

        me = "*****@*****.**"
        you = re.split(r'[;,\s]\s*', self.mailto)

        # Create message container - the correct MIME type is multipart/alternative.
        mime = MIMEMultipart('alternative')
        mime['Subject'] = self.mail_subject
        mime['From'] = me
        mime['To'] = self.mailto

        htmlMsg = "<html> <pre> " + msg + "</pre> </html>"
        part1 = MIMEText(msg, 'plain')
        part2 = MIMEText(htmlMsg, 'html')
        mime.attach(part1)
        mime.attach(part2)

        try:
            autopsy_logger.info("Sending mail to: " + self.mailto)
            server = smtplib.SMTP('localhost')
            server.set_debuglevel(0)

            server.sendmail(me, you, mime.as_string())
            server.quit()
        except socket.error as e:
            autopsy_logger.error(
                "Couldn't send mail, check your local SMTP client: " + str(e))
Beispiel #6
0
    def setBwInterface(self, interface, downSpeed, upSpeed, unit="kbit"):
        """
        :param interface:
        :param downSpeed:
        :param upSpeed:
        :param unit: Valid units are "kbps" - Kilo Bytes/s, "mbps" - Mega Bytes/s ,
                                     "kbit" - Kilo Bits/s , "mbit" - Mega Bits/s , "bps" - Bytes/s
        :return:
        """
        if not interface:
            autopsy_logger.error("Interface can't be None/Empty")
            return False

        autopsy_logger.info("Setting (up/down) speed on interface : ({0}/{1}), {2}".format(upSpeed, downSpeed, interface))
        # self.execute("sudo wondershaper {0} {1} {2}".format(interface, downSpeed, upSpeed))
        self.execute("sudo tc qdisc del dev {2} root;"
                     "sudo tc qdisc add dev {2} root handle 1: htb default 99;"
                     "sudo tc class add dev {2} classid 1:99 htb rate {0}{1} ceil {0}{1} burst 1000k;"
                     "sudo tc class add dev {2} classid 1:1 htb rate 10mbit ceil 10mbit burst 1000k;"
                     "sudo tc filter add dev {2} protocol ip parent 1:0 prio 0 u32 match ip sport 22 0xffff flowid 1:1"
                     .format(upSpeed, unit, interface), quiet=True)

        if self.ssh_client.exit_status_last_command != 0:
            autopsy_logger.error("Error setting bw limits, exiting...")
            return False

        return True
Beispiel #7
0
    def reboot(self, timeout=750):

        autopsy_logger.info("Rebooting the device: " + self.hostname)

        self.execute("sudo /sbin/reboot", quiet=True, timeout=timeout)

        if self.ssh_client.exit_status_last_command != 0:
            return False

        # To check if the reboot sequence has been initiated
        waittime = time.time() + 30

        while waittime >= time.time():
            try:
                self.connect(retries=1)
                time.sleep(2)
            except:
                # Sleeping. No point in connecting immediately
                time.sleep(10)
                break

        # Reducing 10 seconds as we already slept for 10 secs in above loop
        waittime = time.time() + timeout - 10

        while waittime >= time.time():
            try:
                self.connect(retries=1)
                return True
            except (socket.error, SSHException) as e:
                autopsy_logger.debug("Device didn't comeup, retry..")
                time.sleep(10)

        return False
Beispiel #8
0
 def stopContext(self, context):
     if inspect.isclass(context):
         if TestCore.TestHookHandler.ON_END_TEST_CLASS in autopsy_globals.autopsy_test_hooks.keys(
         ):
             for testHook in autopsy_globals.autopsy_test_hooks[
                     TestCore.TestHookHandler.ON_END_TEST_CLASS]:
                 testHook.exec_hook()
         autopsy_logger.info(
             "################################################################",
             fg_color=autopsy_logger.GREEN)
         autopsy_logger.info('|            Finished Test: ' +
                             context.__name__,
                             fg_color=autopsy_logger.GREEN)
         steps = self.dumpTestSteps()
         if str.lstrip(steps) != '':
             lines = steps.split('\n')
             for line in lines:
                 autopsy_logger.info("|                " + line,
                                     fg_color=autopsy_logger.GREEN)
         autopsy_logger.info(
             "################################################################",
             fg_color=autopsy_logger.GREEN)
     elif inspect.ismodule(context):
         if TestCore.TestHookHandler.ON_END_TEST_SUITE in autopsy_globals.autopsy_test_hooks.keys(
         ):
             for testHook in autopsy_globals.autopsy_test_hooks[
                     TestCore.TestHookHandler.ON_END_TEST_SUITE]:
                 testHook.exec_hook()
         autopsy_logger.info("Finished Execution of test suite: " +
                             context.__name__)
Beispiel #9
0
        def new_func(*args, **kwargs):
            result = None
            for i in range(count):
                result = func_name(*args, **kwargs)
                autopsy_logger.info(
                    "Repeating the function '{0}' {1}{2} time".format(func_name, i + 1, get_ordinal_indicator(i + 1)))
                time.sleep(repeatDelay)

            return result
Beispiel #10
0
def signalHandler(signum, frame):
    if signum == signal.SIGTERM or signum == signal.SIGINT:
        autopsy_logger.info(
            "*************** Terminating as per user request ***************")
        exit(2, archive=True)
    elif signum == signal.SIGUSR1:
        pdb.set_trace()
        return

    exit(1)
Beispiel #11
0
    def disconnect(self):
        """ Disconnect from SSH server
        :return: Returns nothing
        """
        if not self.isConnected():
            return

        autopsy_logger.info("Disconnecting host: " + self.host)

        self.close_async()
        if self.handle:
            self.handle.close()
Beispiel #12
0
    def clearBwInterface(self, interface):
        if not interface:
            autopsy_logger.error("Interface can't be None/Empty")
            return False

        autopsy_logger.info("Clear BW params on interface " + interface)
        self.execute("sudo tc qdisc del dev {0} root".format(interface), quiet=True)

        if self.ssh_client.exit_status_last_command != 0:
            autopsy_logger.error("Error clearing bw limits, exiting...")
            return False

        return True
Beispiel #13
0
    def addFailure(self, test, err, capt=None, tb_info=None):
        id = test.id()
        tb = format_exception(err, self.encoding)
        self.stats['fail'] += 1
        try:
            (modulename, classname, testname) = id.split('.')
        except Exception as e:
            autopsy_logger.error("ID: " + str(id))
            autopsy_logger.error(e.message)
            return

        #     autopsy_logger.error("REASON: " + format_exception(err, self.encoding))
        autopsy_logger.error("===========================================")
        autopsy_logger.error("|      Test Failed : " + classname + "." +
                             testname)
        autopsy_logger.error("===========================================")
        timetaken = self._timeTaken()
        # autopsy_logger.info(timetaken)
        self.total_run_time += timetaken

        if autopsy_globals.test_fail_reason.find("\n") != -1:
            autopsy_globals.test_fail_reason = autopsy_globals.test_fail_reason[0:autopsy_globals.test_fail_reason.find("\n")]\
                .strip()

        self.report_string += "\n|{:<40}|{:^10}|{:^20}|{:<86}|"\
            .format("    " + classname + ("" if testname.strip() == "test" else "." + testname), "FAIL", self.nice_to_see_time(timetaken),
                    "   " + autopsy_globals.test_fail_reason.strip())

        self.fail_report_string += '\n' + "#" * 50 + '\n'
        self.fail_report_string += '\nTest Case    : ' + classname + "." + testname
        self.fail_report_string += '\nDescription  : \n' + self.reindent(
            self.currTestDescription, 5)
        self.fail_report_string += '\nSteps : \n' + self.reindent(
            self.dumpTestSteps(), 5)
        self.fail_report_string += '\nFail Reason  : \n' + self.reindent(
            format_exception(err, self.encoding), 5)

        if "test" == testname:
            testcase = self.getTestByName(classname)
            testcase.result = "Failed"
            autopsy_globals.dumpTestCaseJsonFile()

        else:
            testcase = self.getTestByName(classname + "." + testname)
            testcase.result = "Failed"
            autopsy_globals.dumpTestCaseJsonFile()

        if is_pause_on_fail():
            autopsy_logger.info(
                "Pausing the test run as pause on fail file found")
            pdb.set_trace()
Beispiel #14
0
    def startTest(self, test):
        id = test.id()
        (modulename, classname, testname) = id.split('.')
        self.stats['total'] += 1

        if testname != "test":
            testcase = self.getTestByName(classname + "." + testname)
        else:
            testcase = self.getTestByName(classname)

        testcase.description = self.currTestDescription.replace('\n', '\\n')
        testcase.result = "InProgress"
        autopsy_globals.dumpTestCaseJsonFile()

        TestCore.startTest(testcase)
        # self.log_file.write("Test started: "+id_split(id)[0] + "\n")
        autopsy_logger.info("===========================================")
        autopsy_logger.info("|      Test Started : " + classname + "." +
                            testname)
        autopsy_logger.info("===========================================")

        if TestCore.TestHookHandler.ON_START_TEST in autopsy_globals.autopsy_test_hooks.keys(
        ):
            for testHook in autopsy_globals.autopsy_test_hooks[
                    TestCore.TestHookHandler.ON_START_TEST]:
                testHook.exec_hook()

        if is_pause_test_run():
            autopsy_logger.info("Pausing the test run as pause file found")
            pdb.set_trace()
Beispiel #15
0
    def close_connections(self, quick=False):
        autopsy_logger.debug("Closing all connections of testbed")

        if not (quick or self.no_download_logs):
            autopsy_logger.info("Downloading all logs, please wait....")

            progressBar(0, 1)
            if self.host:
                map(
                    lambda node: node.download_all_logs(
                        autopsy_globals.autopsy_logfile), self.host)
            progressBar(1, 1)

        if self.host:
            map(lambda node: node.disconnect() if node else "", self.host)
Beispiel #16
0
def visual_sleep(period, descr=""):
    if not time:
        return

    _timeout = time.time() + period

    if descr:
        autopsy_logger.info(descr),

    autopsy_logger.info("Sleeping for {0} seconds:".format(period))
    _slept_time = 0
    progressBar(_slept_time, period, percentWise=False, countDown=True, prefix="s")

    while time.time() < _timeout:
        time.sleep(1)
        _slept_time += 1
        progressBar(_slept_time, period, percentWise=False, countDown=True, prefix="s")
Beispiel #17
0
    def addSuccess(self, test, capt=None):
        id = test.id()
        self.stats['pass'] += 1
        (modulename, classname, testname) = id.split('.')
        autopsy_logger.info("===========================================")
        autopsy_logger.info("|      Test Passed : " + classname + "." +
                            testname)
        autopsy_logger.info("===========================================")
        timetaken = self._timeTaken()
        self.total_run_time += timetaken

        if autopsy_globals.test_fail_reason.find("\n") != -1:
            autopsy_globals.test_fail_reason = autopsy_globals.test_fail_reason[0:autopsy_globals.test_fail_reason.find("\n")]\
                .strip()

        self.report_string += "\n|{:<40}|{:^10}|{:^20}|{:<86}|"\
            .format("    " + classname + ("" if testname.strip() == "test" else "." + testname), "PASS", self.nice_to_see_time(timetaken),
                    "   " + autopsy_globals.test_fail_reason.strip())

        self.pass_report_string += '\n' + "#" * 50 + '\n'
        self.pass_report_string += '\nTest Case    : ' + classname + "." + testname
        self.pass_report_string += '\nDescription  : \n' + self.reindent(
            self.currTestDescription, 5)
        self.pass_report_string += '\nSteps : \n' + self.reindent(
            self.dumpTestSteps(), 5)

        if "test" == testname:
            testcase = self.getTestByName(classname)
            testcase.result = "Passed"
            autopsy_globals.dumpTestCaseJsonFile()
        else:
            testcase = self.getTestByName(classname + "." + testname)
            testcase.result = "Passed"
            autopsy_globals.dumpTestCaseJsonFile()
Beispiel #18
0
    def getIpAddress(self, iface):

        if not iface:
            autopsy_logger.error("Interface name cannot be empty")
            return False

        autopsy_logger.info("Checking ip for interface: " + iface)
        ifcfg = self.execute("sudo ifconfig {0}".format(iface), quiet=True)

        # TODO - We need to make this condition more robust
        if iface in ifcfg:
            ip = re.search(r'inet addr:(\S+)', ifcfg)
            if ip:
                ip_address = ip.group(1)

                return ip_address

        elif iface not in ifcfg:
            autopsy_logger.error("Interface:".format(iface) + " does not exist on this machine")
            return False

        return False
Beispiel #19
0
    def injectErrorsinfile(self, f):
        fileLocation = f.rsplit('/', 2)[0]
        fileName = f.rsplit('/', 1)[-1]
        mountPoint = self.execute("df -k {0}".format(f))
        mountPoint = mountPoint.rsplit('\n')[1].rsplit(' ')[0]

        if not f:
            autopsy_logger.error("Please Provide a file to inject errors into...")
            return False

        # self.ssh_client.connect()

        if not self.isFileExists(f):
            autopsy_logger.info("Creating file as it doesn't exist on source...")
            self.createFile(filePath=fileLocation, fileName=fileName, size="1G", randomData=True)

        diskSize = self.execute("blockdev --getsz {0}".format(mountPoint), sudo=True)

        autopsy_logger.info("Creating linear device...")

        self.execute("umount {0}".format(fileLocation))

        self.execute("dmsetup create img 0 {0} linear {1} 0".format(diskSize, mountPoint))

        self.execute("dmsetup table img")

        self.execute("mount /dev/mapper/img {0} && cd {0}".format(fileLocation), sudo=True)

        fileDetails = self.execute("hdparm {0}".format(f))

        columns = fileDetails.split(' ')

        autopsy_logger.info("Introducing errors in last 64K of the file")

        self.execute("umount {0}".format(fileLocation), sudo=True)

        beginErrorAt = columns[1].split('\n')[-1]
        beginErrorRange = columns[3].split('\n')[-1]
        endErrorStart = int(columns[2].split('\n')[-1]) + 1
        endErrorRange = int(diskSize) - endErrorStart

        cmd = "echo -e 0 {0} linear {1} 0\n" \
              "{0} {2} error\n{3} {4} linear /dev/sdb1 {3}" \
              " | dmsetup load img".format(beginErrorAt, mountPoint, beginErrorRange, endErrorStart, endErrorRange)

        self.execute(cmd, sudo=True)

        self.execute("dmsetup resume img", sudo=True)
        self.execute("dmsetup load img", sudo=True)

        self.execute("mount /dev/mapper/img {0}".format(fileLocation))
    def _run_send_input(self, session, stdin, input_data):
        """
        Send the input data.

        @param session     The session.
        @param stdin       The stdin stream for the session.
        @param input_data  The input data (default is None).
        """
        if input_data is not None:
            autopsy_logger.info('session.exit_status_ready() {0}'.format(
                str(session.exit_status_ready())))
            autopsy_logger.info('stdin.channel.closed {0}'.format(
                str(stdin.channel.closed)))
            if stdin.channel.closed is False:
                autopsy_logger.info('sending input data')
                stdin.write(input_data)
Beispiel #21
0
    def execute(self,
                command,
                inputValues=None,
                timeout=EXEC_TIMEOUT,
                quiet=False,
                sudo=False):
        """
        :param sudo:
        :param inputValues: List if you need to answer some interactive questions
                        in the command. Pass in the same order they may occur in command output
        :param quiet:
        :param timeout: Timeout if the command is taking long time to return
        :param command: Command to execute in the SSH terminal
                        Connects to SSH if not already connected

                        If you are looking for polling a command output or
                        the command has interactiveness, you can use 'run'
                        proc instead of this.

                        Pass 'inputValues' list if you need to answer some interactive questions
                        in the command. Pass in the same order they may occur in command output

        :return: Returns the output of the command
        """

        with self.max_session_lock:
            if not self.isConnected():
                # Retrying 10 times, when this host was connected some time back and
                #    now reconnecting because of some problem.
                # Otherwise, if it is first time being connected retry only 2 times as
                #    it doesn't make much sense to waste time.
                # Same is the case with timeout
                self.connect(retries=10 if self.connected else 1,
                             timeout=min(timeout,
                                         (60 if self.connected else 10)))

            if not inputValues:
                inputValues = []

            if type(inputValues) is not list:
                inputValues = [inputValues]

            if command.startswith("sudo"):
                command = command.replace("sudo ", "")
                sudo = True

            feed_password = False
            if sudo and self.user != "root":
                if "bash " in command:
                    autopsy_logger.critical(
                        "Executing sudo commands with bash is not supported")
                    return "Executing sudo commands with bash is not supported"

                # Escape double-quotes if the command is having double quotes in itself
                command = command.replace('"', '\\"')
                command = "sudo -k -S -p '' bash -c \"{0}\"".format(command)
                feed_password = self.root_password is not None and len(
                    self.root_password) > 0

            self.last_executed_command = command
            self.last_executed_command_inp_values = inputValues

            retries = 3
            stdin, stdout, stderr = None, None, None

            while retries > 0:
                try:
                    if not quiet:
                        autopsy_logger.info(
                            "Exec Cmd" + ((" (" + self.hostname +
                                           "): ") if self.hostname else ": ") +
                            command,
                            bold=True)
                    else:
                        autopsy_logger.debug(
                            "Executing command " +
                            ((" (" + self.hostname +
                              "): ") if self.hostname else ": ") + command,
                            bold=True)
                    stdin, stdout, stderr = self.handle.exec_command(
                        command=command,
                        timeout=timeout
                        if timeout is not None else self.EXEC_TIMEOUT,
                        get_pty=True)

                    if stdin and stdout and stderr:
                        break
                except (SSHException, socket.timeout, socket.error,
                        EOFError) as e:
                    if retries == 0:
                        autopsy_logger.error(
                            "Error executing command even after retries")
                        self.connected = False
                        raise e

                    autopsy_logger.debug(
                        "Exception executing command, retrying")

                retries -= 1
                time.sleep(0.1)

            if retries <= 0:
                autopsy_logger.critical(
                    "Couldn't execute the command. Probably n/w issue or timeout: "
                    + command)
                self.connected = False
                raise SSHError("Error executing command")

            # Give a bit of time for the prompt to show up.
            # It works even without this sleep. But if we send the password before prompt, it
            #   gets reflected back on to stdout and password is visible
            # Same is the case with any interactive inputs too.
            time.sleep(0.1)

            try:
                if feed_password and stdin:
                    stdin.write(self.root_password + "\n")
            except socket.error:
                pass

            try:
                if inputValues is not None and len(inputValues) > 0 and stdin:
                    for inp in inputValues:
                        # Same as above sleep for root password
                        time.sleep(0.1)
                        if len(inp) == 1 and ord(inp) < 32:
                            # This IF condition means the input is a special character like, Ctrl + '['
                            # But we need to wait a little more time otherwise this command gets executed so fast that
                            #   even the required prompt will be taken off for the previous command to get executed.
                            #
                            #   e.g., dlpause 1, dlclose 1, Ctrl + '[', quit
                            #      In the above commands, dlclose 1 may be skipped as the next command executed fast and
                            #   left the prompt.

                            time.sleep(1)
                            stdin.write(inp)
                        else:
                            autopsy_logger.debug("Inputting ----> : " + inp)
                            stdin.write(inp + "\n")

                        stdin.flush()

            except socket.error:
                autopsy_logger.warning(
                    "Command finished before taking all the input values")

            output = stdout.read() if stdout else ""
            error = stderr.read() if stderr else ""
            output = output.strip() if output is not None else ""
            error = error.strip() if error is not None else ""

            self.exit_status_last_command = stdout.channel.recv_exit_status()
            self.stderr_last_command = error
            self.stdout_last_command = output

            if not quiet:
                autopsy_logger.info(output)
            else:
                autopsy_logger.debug(output)

            if self.exit_status_last_command != 0:
                if error:
                    autopsy_logger.info(error)

            return output
Beispiel #22
0
def check(condition, fail_msg=None, pass_msg=None,
          descr='', cont=False, run_on_fail=None):
    """

    :param run_on_fail:
    :param condition: Some condition to evaluate to TRUE or FALSE
    :param fail_msg:
    :param pass_msg:
    :param descr:
    :param cont: Not to assert and continue with remaining even on failure,
                run_on_fail will not be called
    :return:
    """
    step = Step()
    # step.stepnum = len(autopsy_globals.test_steps) + 1
    step.stepdescr = descr
    if condition:
        step.setStatus('PASSED')
        if pass_msg is not None:
            # autopsy_logger.info("PASSED: " + pass_msg)
            if str.strip(str(descr)) == '':
                step.stepdescr = pass_msg
            else:
                step.stepdescr += " ({0})".format(pass_msg)

        if str.strip(str(step.stepdescr)) != '':
            autopsy_globals.test_steps.append(step)
            autopsy_logger.info(colored("STEP {0}: {1} - "
                                        .format(step.stepnum, step.stepdescr),
                                        color="magenta", attrs=["bold"]) +
                                colored(step.stepstatus, color="green", on_color=None, attrs=["bold", "dark"]))
    else:
        step.setStatus('FAILED')

        if fail_msg is not None:
            autopsy_logger.error(colored("FAILED: " + fail_msg))
            if str.strip(str(descr)) == '':
                step.stepdescr = fail_msg
        else:
            if str.strip(str(descr)) != '':
                fail_msg = descr + " is FAILED"
            else:
                fail_msg = "Test Step Failed"

        if str.strip(str(step.stepdescr)) != '':
            autopsy_globals.test_steps.append(step)
            autopsy_logger.info(colored("STEP {0}: {1} - "
                                        .format(step.stepnum, step.stepdescr),
                                        color="magenta", attrs=["bold"]) +
                                colored(step.stepstatus, color="red", on_color=None, attrs=["bold", "dark"]))

        if len(autopsy_globals.test_fail_reason) > 0:
            autopsy_globals.test_fail_reason += '\n'

        autopsy_globals.test_fail_reason += fail_msg if len(fail_msg) < 80 else fail_msg[:70] + '...'
        if not cont:
            if run_on_fail is not None:
                if type(run_on_fail) is list:
                    for func in run_on_fail:
                        func()
                else:
                    run_on_fail()

            assert False, fail_msg
        else:
            # if run_on_fail is not None:
            #     autopsy_logger.warning("Run-On-Fail will not be called when cont is True")
            pass
    def _run_poll(self, session, timeout, input_data):
        """
        Poll until the command completes.

        @param session     The session.
        @param timeout     The timeout in seconds.
        @param input_data  The input data.
        @returns the output
        """
        interval = 0.1
        maxseconds = timeout
        maxcount = maxseconds / interval

        # Poll until completion or timeout
        # Note that we cannot directly use the stdout file descriptor
        # because it stalls at 64K bytes (65536).
        input_idx = 0
        timeout_flag = False
        autopsy_logger.debug('polling (%d, %d)' % (maxseconds, maxcount))
        start = datetime.datetime.now()
        start_secs = time.mktime(start.timetuple())
        # output = ''
        session.setblocking(0)
        while True and not self.is_stop:
            if session.recv_ready():
                data = session.recv(self.bufsize)
                self.output += data
                self.incremental_output += data
                autopsy_logger.debug(data)
                self.file.write(data)
                self.file.flush()
                autopsy_logger.debug('read %d bytes, total %d' %
                                     (len(data), len(self.output)))

                if session.send_ready():
                    # We received a potential prompt.
                    # In the future this could be made to work more like
                    # pexpect with pattern matching.
                    if input_idx < len(input_data):
                        data = input_data[input_idx] + '\n'
                        input_idx += 1
                        autopsy_logger.info('sending input data {0}'.format(
                            len(data)))
                        session.send(data)

            autopsy_logger.debug('session.exit_status_ready() = {0}'.format(
                str(session.exit_status_ready())))
            if session.exit_status_ready():
                break
            if timeout != 0:
                # Timeout check
                now = datetime.datetime.now()
                now_secs = time.mktime(now.timetuple())
                et_secs = now_secs - start_secs
                autopsy_logger.debug('timeout check %d %d' %
                                     (et_secs, maxseconds))
                if et_secs > maxseconds:
                    autopsy_logger.info('polling finished - timeout')
                    timeout_flag = True
                    break

        autopsy_logger.info('polling loop ended')
        if session.recv_ready():
            data = session.recv(self.bufsize)
            self.output += data
            self.incremental_output += data
            autopsy_logger.info('read %d bytes, total %d' %
                                (len(data), len(self.output)))

        autopsy_logger.info('polling finished - %d output bytes' %
                            (len(self.output)))
        if timeout_flag:
            autopsy_logger.info('appending timeout message')
            session.close()
Beispiel #24
0
    def startContext(self, context):
        if inspect.isclass(context):
            autopsy_logger.info(
                "################################################################",
                fg_color=autopsy_logger.GREEN)
            autopsy_logger.info('|            Starting Test: ' +
                                context.__name__,
                                fg_color=autopsy_logger.GREEN)
            if context.__doc__ is not None:
                self.currTestDescription = str.strip(str(context.__doc__))
                autopsy_logger.info('|            Description:',
                                    fg_color=autopsy_logger.GREEN)
                lines = context.__doc__.split('\n')
                for line in lines:
                    autopsy_logger.info("|                " + line,
                                        fg_color=autopsy_logger.GREEN)

            autopsy_logger.info(
                "################################################################",
                fg_color=autopsy_logger.GREEN)
            if TestCore.TestHookHandler.ON_START_TEST_CLASS in autopsy_globals.autopsy_test_hooks.keys(
            ):
                for testHook in autopsy_globals.autopsy_test_hooks[
                        TestCore.TestHookHandler.ON_START_TEST_CLASS]:
                    testHook.exec_hook()
        elif inspect.ismodule(context):
            autopsy_logger.info("Starting Execution of test suite: " +
                                context.__name__)
            if TestCore.TestHookHandler.ON_START_TEST_SUITE in autopsy_globals.autopsy_test_hooks.keys(
            ):
                for testHook in autopsy_globals.autopsy_test_hooks[
                        TestCore.TestHookHandler.ON_START_TEST_SUITE]:
                    testHook.exec_hook()
Beispiel #25
0
        if not args.quick:
            testbedInitTestCase = TestCase(
                "TestbedInit", "NotStarted",
                "Initializing/Cleaning the nodes in testbed")
            autopsy_globals.test_list.append(testbedInitTestCase)

        nose.run(addplugins=[AutopsyCollectOnlyPlugin()], argv=list2)

        if args.debug:
            pdb.set_trace()

        signal.signal(signal.SIGUSR1, signalHandler)

        if args.reboot:
            autopsy_logger.info("*** REBOOTING all DP Nodes ***")
            rebootTestCase.result = "InProgress"
            autopsy_globals.dumpTestCaseJsonFile()
            autopsy_globals.autopsy_testbed.reboot_dp_nodes()

            # Waiting for all the processes to start and get settled with CP communication
            visual_sleep(120,
                         "Waiting for all the processes to be up and settled")

            rebootTestCase.result = "Passed"
            autopsy_globals.dumpTestCaseJsonFile()

        if not args.quick:
            testbedInitTestCase.result = "InProgress"
            autopsy_globals.dumpTestCaseJsonFile()
            if not autopsy_globals.autopsy_testbed.openConnections():
    def run(self):
        """
        Run a command with optional input data.

        Here is an example that shows how to run commands with no input:

            ssh = MySSH()
            ssh.connect('host', 'user', 'password')
            status, output = ssh.run('uname -a')
            status, output = ssh.run('uptime')

        Here is an example that shows how to run commands that require input:

            ssh = MySSH()
            ssh.connect('host', 'user', 'password')
            status, output = ssh.run('sudo uname -a', '<sudo-password>')

        @param cmd         The command to run.
        @param input_data  The input data (default is None).
        @param timeout     The timeout in seconds (default is 10 seconds).
        @returns The status and the output (stdout and stderr combined).
        """

        if not self.sshHandle.isConnected():
            self.sshHandle.connect()
        autopsy_logger.info('running command: ({0}) {1}'.format(
            self.timeout, self.command))
        self.transport = self.sshHandle.handle.get_transport()

        if self.transport is None:
            autopsy_logger.info('no connection to host')
            return -1, 'ERROR: connection not established\n'

        # Fix the input data.
        input_data = self._run_fix_input_data(self.input_data)

        autopsy_logger.info("Creating file: " + self.fileName)

        self.file = open(self.fileName, 'a+')
        # Initialize the session.
        autopsy_logger.info('initializing the session')

        session = self.transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        session.exec_command(self.command)

        self._run_poll(session, self.timeout, input_data)
        status = session.recv_exit_status()
        autopsy_logger.info('output size %d' % (len(self.output)))
        autopsy_logger.info('status %d' % (status))
        return status, self.output
Beispiel #27
0
    def report(self, stream):
        self.log_file = codecs.open(self.log_file_name, 'w', self.encoding,
                                    'replace')

        ipaddr = ''
        try:
            ipaddr = socket.gethostbyname(socket.gethostname())
        except Exception as e:
            autopsy_logger.error(e.message)
        self.report_string1 = "\n                                  AUTOMATION SUMMARY REPORT\n"
        self.report_string1 += "                                  -------------------------\n\n"
        self.report_string1 += "\nLog Loc   : {0}".format(
            self.archive_loc) + "/"
        self.report_string1 += "\nTestbed   : {0}".format(
            autopsy_globals.autopsy_testbed.tbname)
        self.report_string1 += "\nRun Time  : {0}".format(
            self.nice_to_see_time(self.total_run_time))
        self.report_string1 += "\nCmd Line  : {0}".format(
            str(' '.join(sys.argv)))
        self.report_string1 += "\nExec Host : {0}".format(ipaddr)
        self.report_string1 += "\n"
        self.report_string1 += "\nTotal     : {0}".format(self.stats['total'])
        self.report_string1 += "\nPass      : {0}".format(self.stats['pass'])
        self.report_string1 += "\nFail      : {0}".format(self.stats['fail'])
        self.report_string1 += "\nError     : {0}".format(self.stats['error'])
        self.report_string1 += "\n"
        self.report_string += '\n ' + '-' * 159

        self.mail_subject = 'Automation Report - ({4}) - Total: {0}, Pass: {1}, Fail: {2}, Err: {3}'\
                                .format(self.stats['total'], self.stats['pass'], self.stats['fail'], self.stats['error'],
                                        ", ".join(autopsy_globals.autopsy_test_suites))

        self.report_string = self.report_string1 + self.report_string

        if self.fail_report_string != '':
            self.fail_report_string = '\n\n                     Diagnostics of Failed Tests' \
                                      + '\n                     ---------------------------\n' \
                                      + self.fail_report_string
            self.fail_report_string += '\n------------------------------------------------------------------------------------------------------\n\n'

        if self.err_report_string != '':
            self.err_report_string = '\n                     Diagnostics of Errored Tests' \
                                     + '\n                     ----------------------------\n' \
                                     + self.err_report_string
            self.err_report_string += '\n------------------------------------------------------------------------------------------------------\n\n'

        if self.pass_report_string != '':
            self.pass_report_string = '\n                     Diagnostics of Passed Tests' \
                                      + '\n                     ---------------------------\n' \
                                      + self.pass_report_string
            # self.pass_report_string += '\n------------------------------------------------------------------------------------------------------\n\n'

        self.report_string += self.fail_report_string
        self.report_string += self.err_report_string
        self.report_string += self.pass_report_string

        autopsy_logger.info(self.report_string)
        self.log_file.write(self.report_string)
        self.log_file.close()

        self.sendmail(self.report_string)