コード例 #1
0
ファイル: autorun.py プロジェクト: ruler501/acrTestingScripts
def main(argv=None):
	global shouldExit
	global childPID
	if argv == None:
		argv = sys.argv
	for i in xrange(len(argv)):
		if argv[i] == "--log":
			log = open(argv[i+1],'w')
			break
	else:
		log = open('debug.log','w')
	print "Starting child"
	child = spawn("gdb -quiet -fullname -args "+ACRcommand(), logfile=log)
	child.expect_exact('(gdb)')
	print "Loading Scripts"
	child.sendline('source client.py')
	child.expect_exact('(gdb)')
	print "Running child"
	child.sendline('r')
	child.expect(r"New Thread \d+\.")
	try:
		childPID = int(child.after.split('.')[0].split()[-1])
	except ValueError:
		print "Couldn't find the child's PID"
	if "--ucontrol" in argv:
		child.interact()
	else:
		try:
			while child.isalive():
				i = child.expect_exact(['(gdb)', 'exited with code', TIMEOUT], timeout=1)
				if i == 0:
					log.write("ERROR ABOVE\n")
					print "continuing"
					child.sendline('c')
				elif i == 1:
					log.write("Exited\n")
					log.close()
					return 0
				elif i == 2:
					if checkRAM():
						log.write("Memory Overflow")
						child.kill(5)
						#child.terminate()
					if shouldExit:
						print "Exitting"
						child.terminate()
		except EOF:
			pass
	log.close()
	return 0
コード例 #2
0
    def san_switch_download_firmware(self):
        for san_switch_obj in self.my_parser.san_switches_list:
            # NOTE: expect should return 0 if 'successful' exists within the
            # output

            # here, check model and create object of corresponding class
            if 'SN6000B' in san_switch_obj.model:

                creds = san_switch_obj.ip_address + ';' + \
                    san_switch_obj.username + ';' + \
                    san_switch_obj.password + ';'
                child = spawn('python san_switch.py model %s creds = %s' %
                              (san_switch_obj.model, creds),
                              logfile=file('logs/sn6000firmwarelog.txt', 'w'))
                if san_switch_obj.update == 'True':
                    SENDLINE('my_san.download_firmware(%s, %s, %s, %s)')
コード例 #3
0
    def teardown_network(self):
        """
        """
        for network_switch_obj in self.my_parser.network_switches_list:
            pass

        for san_switch_obj in self.my_parser.san_switches_list:
            if 'SN6000B' in san_switch_obj.model:
                sn_log = os.path.join(os.getcwd(), r"logs",
                                      r"sn6000config.txt")
                try:
                    creds = san_switch_obj.ip_address + ';' + \
                        san_switch_obj.username + ';' + \
                        san_switch_obj.password + ';'
                    child = spawn('python san_switch.py model %s creds = %s' %
                                  (san_switch_obj.model, creds),
                                  logfile=file(sn_log, 'w'))
                    if os.name == 'nt':
                        SENDLINE = child.direct_sendline
                    else:
                        SENDLINE = child.sendline
                    for config in san_switch_obj.zone_configs:
                        SENDLINE('my_san.disable_config(%s)' %
                                 (config.attrib["name"]))
                        child.expect("(yes, y, no, n):")
                        SENDLINE('yes')
                    SENDLINE('my_san.terminate_connection()')
                    child.terminate()
                    if child.isalive():
                        log._warn(
                            "CHILD PROCESS FAILED TO TERMINATE, PLEASE FILE BUG"
                        )
                except Exception:
                    log._warn(
                        "Failed to start child process for SAN switch configuration"
                    )
                    # elif 'some other model' in san_switch_obj.model:
                # configure that model
            else:
                log._warn("Model not supported by Config manager at this time")
コード例 #4
0
    def configure_network(self):
        """
        One of the main threads of Config Manager, configures network
        and SAN switches based on what is present in input XML
        """
        for network_switch_obj in self.my_parser.network_switches_list:
            sw_obj = switch.SwitchCfg(network_switch_obj.ip_address,
                                      network_switch_obj.username,
                                      network_switch_obj.password,
                                      network_switch_obj.tftp_server_ip,
                                      network_switch_obj.config_file_name)
            '''
            sw_obj.upload_switch_config_file_to_tftp_server()
            sw_obj.download_switch_config_file_to_switch()
            '''
            lista = []
            for vlan in network_switch_obj.vlans:
                vlan_dict = vlan.attrib
                vlan_dict['name'] = vlan.tag
                # print vlan_dict
                lista.append(vlan_dict)
                for i in lista:
                    untag = i["UntaggedPorts"]
                    vlan_id = i["ID"]
                    tagged = i["TaggedPorts"]
                    # sw_obj.create_vlan(vlan_id)
                if vlan_id == 'None':
                    log._info(
                        "There are no VLAN's defined to be created, Hence Tagging and Untagging of ports will be skipped"
                    )
                    log._info(
                        "Please define a VLAN to be created with tag %s so, ports could be tagged or untagged"
                        % vlan.tag)
                else:
                    log._info("Creating VLAN %s" % vlan_id)
                    sw_obj.create_vlan(vlan_id)
                    untagged_ports = untag.split(',')
                    tagged_ports = tagged.split(',')

                    if untagged_ports == 'None':
                        log._info("There are no ports to be untagged")
                    else:
                        for port in untagged_ports:
                            log._info("untagging port %s to vlan %s" %
                                      (port, vlan_id))
                            sw_obj.untag_ports_to_vlan(vlan_id, port)

                    if tagged_ports == 'None':
                        log._info("There are no ports to be tagged")
                    else:
                        for port in tagged_ports:
                            log._info("tagging port %s to vlan %s" %
                                      (port, vlan_id))
                            sw_obj.tag_ports_to_vlan(vlan_id, port)
            user_list = []
            for user in network_switch_obj.users:
                user_dict = user.attrib
                user_dict['name'] = user.tag
                # print user_dict
                user_list.append(user_dict)
                for i in user_list:
                    user_name = i["Username"]
                    user_pw = i["Password"]
                    sw_obj.configure_users(user_name, user_pw)

            port_list = []
            for port in network_switch_obj.ports:
                port_dict = port.attrib
                port_dict['name'] = port.tag
                port_list.append(port_dict)
            for i in port_list:
                port_nu = i['PortList']
                port_state = i['PortState']
                port_duplex = i['PortDuplex']
                port_speed = i['PortSpeed']
                # print port_number, port_state, port_duplex, port_speed
                if port_nu == 'None':
                    log._warn(
                        "There are no ports mentioned for port attribute configuration under xml tag %s"
                        % port.tag)
                else:
                    log._info(
                        "There ports mentioned to be configured with port attributes"
                    )
                    port_number = port_nu.split(',')
                    for po in port_number:
                        if port_state == 'None':
                            log._info(
                                "port attribute state will not be configured as the value of it xml is set to None"
                            )
                        else:
                            log._info(
                                "Port attribute state will be configured for port %s "
                                % po)
                            sw_obj.configure_port_state(po, port_state)
                        if port_duplex == 'None':
                            log._info(
                                "port attribute duplex will not be configured as the value of it xml is set to None"
                            )
                        else:
                            log._info(
                                "Port attribute duplex will be configured for port %s "
                                % po)
                            sw_obj.configure_port_duplex_mode(po, port_duplex)
                        if port_speed == 'None':
                            log._info(
                                "port attribute speed will not be configured as the value of it xml is set to None"
                            )
                        else:
                            log._info(
                                "Port attribute speed will be configured for port %s "
                                % po)
                            sw_obj.configure_port_speed(po, port_speed)

        for san_switch_obj in self.my_parser.san_switches_list:
            # NOTE: expect should return 0 if 'successful' exists within the
            # output

            # here, check model and create object of corresponding class
            if 'SN6000B' in san_switch_obj.model:

                creds = san_switch_obj.ip_address + ';' + \
                    san_switch_obj.username + ';' + \
                    san_switch_obj.password + ';'
                sn_log = os.path.join(os.getcwd(), r"logs",
                                      r"sn6000config.txt")
                try:
                    child = spawn('python san_switch.py model %s creds = %s' %
                                  (san_switch_obj.model, creds),
                                  logfile=file(sn_log, 'w'))
                    # port zoning to go here later
                    if os.name == 'nt':
                        SENDLINE = child.direct_sendline
                    else:
                        SENDLINE = child.sendline
                    # if there are zone configs present
                    if san_switch_obj.zone_configs:
                        for config in san_switch_obj.zone_configs:
                            # create zones with added wwns
                            # zone elements!
                            zone_list = [zone for zone in config.find("Zones")]
                            for zone in zone_list:
                                # compile the list of hosts to be added to zone
                                host_list = [
                                    host for host in zone.find("Hosts")
                                ]
                                for host in host_list:
                                    # compile the list of wwns to add to host
                                    wwn_list = [
                                        wwn.attrib["wwn"]
                                        for wwn in host.find('WWNs')
                                    ]
                                    SENDLINE('my_san.create_alias(%s, %s)' %
                                             (host.attrib['alias'], wwn_list))
                                    # no need to send a y for creating alias
                                    # expect should return 0 if 'successful'
                                    # exists within the output
                                    if child.expect("successful"):
                                        log._warn(
                                            "Failed to create host %s with given WWNs or domain/port index list"
                                            % (host.attrib['alias']))
                                    del wwn_list[:]
                                SENDLINE('my_san.create_zone(%s,%s)' %
                                         (zone.attrib["alias"], host_list))
                                # no need to send a y for creating a zone
                                if child.expect("successful"):
                                    log._warn(
                                        "Failed to create zone %s with given host list"
                                        % (zone.attrib['alias']))
                                del host_list[:]
                            # compile the list of zones to be added to config
                            SENDLINE('my_san.create_config(%s,%s)' %
                                     (config.attrib["name"], zone_list))
                            # no need to send a y for creating a zone
                            if child.expect("successful"):
                                log._warn(
                                    "Failed to create conig %s with given zone list"
                                    % (config.attrib["name"]))
                            del zone_list[:]
                        # here, use winpexpect to answer the decision prompts
                        # from SN6000 switch
                    if san_switch_obj.ports:
                        for port in san_switch_obj.ports:
                            port_num = port.tag.strip("PORTport")
                            SENDLINE('my_san.set_port_speed(%s,%s)' %
                                     (port_num, port.attrib["Speed"]))
                            # no need to send a y for creating a zone
                            if child.expect("successful"):
                                log._warn(
                                    "Failed to set port speed for port %s" %
                                    (port_num))
                            SENDLINE('my_san.set_port_fillword(%s, %s)' %
                                     (port_num, port.attrib["Fillword"]))
                            if child.expect("successful"):
                                log._warn(
                                    "Failed to set port fillword for port %s" %
                                    (port_num))
                    SENDLINE('my_san.save_config()')
                    child.expect("(yes, y, no, n):")
                    SENDLINE('yes')
                    SENDLINE('my_san.enable_config(%s)' %
                             (config.attrib["name"]))
                    child.expect("(yes, y, no, n):")
                    SENDLINE('yes')
                    SENDLINE('my_san.terminate_connection()')
                    child.terminate()
                    if child.isalive():
                        log._warn(
                            "CHILD PROCESS FAILED TO TERMINATE, PLEASE FILE BUG"
                        )
                except Exception:
                    log._warn(
                        "Failed to start child process for SAN switch configuration"
                    )
            # elif 'some other model' in san_switch_obj.model:
            # configure that model

            else:
                log._warn("Model not supported by Config manager at this time")
コード例 #5
0
ファイル: ciserver.py プロジェクト: geertj/ciserver
 def run_tests(self):
     """Run the tests via the controller."""
     jobid = self.job['id']
     logger = self.logger
     ctrl = self.job['environment']['controller']
     vms = self.client.meta_vms(self.appid).vms
     for vm in vms:
         if vm.name.lower() == ctrl['host'].lower():
             break
     else:
         raise JobFailed('Controller VM not found: %s' % name)
     host = vm.vmDynamicMD.fullyQualifiedDomainName
     repo = self.job['project']['repo']
     logger.debug('[job %s] Running tests via "ssh" controller', jobid)
     logger.debug('[job %s] Controller node = %s', jobid, host)
     ssh = winpexpect.spawn('ssh-agent sh', timeout=30)
     try:
         # Forward the repository key.
         keyfile = os.path.join(self.scheduler.directory, 'keys', repo['key'])
         ssh.expect('[$#]')
         ssh.send('ssh-add %s\n' % keyfile)
         ssh.expect('[$#]')
         ssh.send('ssh -A ravello@%s\n' % host)
         # Install a more distinctive prompt that hopefully does not occur
         # in the output of any command we run.
         ssh.expect('[#$]')
         prompt = 'CITestHost: '
         ssh.send('PS1="%s"\n' % prompt)
         ssh.expect(prompt)  # echo
         ssh.expect(prompt)  # prompt
         # Check out the commit in a temporary directory
         url = repo['url']
         parsed = urlparse.urlsplit(url)
         #repodir = parsed.path.rstrip('/').split('/')[-1].rstrip('.git')
         logger.debug('[job %s] cloning source code from %s', jobid, url)
         dirname = os.urandom(8).encode('hex')
         ssh.send('mkdir %s\n' % dirname)
         ssh.expect(prompt)
         ssh.send('cd %s\n' % dirname)
         ssh.expect(prompt)
         ssh.send('git clone %s\n' % url)
         ssh.expect(prompt)
         ssh.send('cd *\n')
         ssh.expect(prompt)
         commit = self.job['commit']['id']
         logger.debug('[job %s] checkout commit %s', jobid, commit)
         ssh.send('git checkout %s\n' % commit)
         ssh.expect(prompt)
         # And run the tests!
         command = ctrl['command']
         logger.debug('[job %s] running test command "%s"', jobid, command)
         ssh.send('%s\n' % command)
         ssh.settimeout(600)
         ssh.expect('\r\n')  # echo
         ssh.expect(prompt)
         output = ssh.before[:ssh.before.rfind('\r\n')]  # strip prompt
         ssh.settimeout(30)
         ssh.send('echo $?\n')
         ssh.expect('\r\n')  # echo
         ssh.expect('\r\n')  # end of output
         status = int(ssh.before)
         ssh.expect(prompt)  # end of output
         ssh.send('cd ../..\n')
         ssh.expect(prompt)
         ssh.send('rm -rf %s\n' % dirname)
         ssh.expect(prompt)
         ssh.send(ssh.cchar('VEOF'))  # exit ssh
         ssh.expect('[$#]')
         ssh.send(ssh.cchar('VEOF'))  # exit ssh-agent
         ssh.wait(10)
     except (TIMEOUT, EOF):
         logger.debug('[job %s] failed to run the test', jobid)
         ssh.terminate()
         raise JobFailed('Failed to run test job')
     logger.debug('[job %s] test return code: %s', jobid, status)
     self.status = status
     self.output = output
コード例 #6
0
parser.add_argument('-f',
                    dest='final',
                    metavar='FINAL_STRING',
                    type=str,
                    help='Final string')
parser.add_argument('arguments',
                    metavar='ARGS',
                    type=str,
                    nargs='*',
                    help='Arguments for program')

args = parser.parse_args()

print('Running "{0}" for a maximum time of {1} seconds.'.format(
    args.program, args.timeout))
p = spawn(args.program, args.arguments)
start = time.time()
timeout = False
finalseen = False
try:
    while True:
        p.expect('\n', start + args.timeout - time.time())
        data = p.before
        if isinstance(data, bytes):
            data = data.decode('string_escape' if sys.version_info < (
                3, 0) else 'unicode_escape')
        print(data)
        if args.final and args.final in data:
            finalseen = True
except pexpect.EOF:
    pass
コード例 #7
0
ファイル: timeout.py プロジェクト: HectorGPala/czmq
  WINDOWS = True
else:
  from pexpect import spawn
  import pexpect
args = sys.argv[1:]

parser = argparse.ArgumentParser(description='Run PROGRAM for limited amount of time')
parser.add_argument('timeout', metavar='TIMEOUT', type=int, help='Timeout in seconds')
parser.add_argument('program', metavar='PROGRAM', type=str, help='Program to execute')
parser.add_argument('-f', dest='final', metavar='FINAL_STRING', type=str, help='Final string')
parser.add_argument('arguments', metavar='ARGS', type=str, nargs='*', help='Arguments for program')

args = parser.parse_args()

print('Running "{0}" for a maximum time of {1} seconds.'.format(args.program, args.timeout))
p = spawn(args.program, args.arguments)
start = time.time()
timeout = False
finalseen = False
try:
  while True:
    p.expect('\n', start + args.timeout - time.time())
    data = p.before
    if isinstance(data, bytes):
      data = data.decode('string_escape' if sys.version_info < (3, 0) else 'unicode_escape')
    print(data)
    if args.final and args.final in data:
      finalseen = True
except pexpect.EOF:
  pass
except pexpect.TIMEOUT: