Example #1
0
def commandReact(command, message, irc):
    arg = {}
    for i in range(0, len(message["args"])):
        arg.update({"arg" + str(i + 1): message["args"][i]})
    if len(message["args"]) < 10:
        for i in range(len(message["args"]), 10):
            arg.update({"arg" + str(i + 1): ""})
    for name in commands:
        c = commands[name]
        if c["reactTo"] == "sender":
            reactTo = common.senderFormat(message["from"], "nick")
        elif c["reactTo"] == "channel":
            if message["to"].split("!")[0] != common.conf.read()["nick"]:
                reactTo = message["to"]
            else:
                reactTo = common.senderFormat(message["from"], "nick")
        if command == name and c["reactType"] == "say":
            common.say(reactTo, common.substitute(c["reactText"], message,
                                                  arg), irc)
            return True
        elif command == name and c["reactType"] == "me":
            common.me(reactTo, common.substitute(c["reactText"], message, arg),
                      irc)
            return True
    return False
def run_scp(local_file, destination):
    scp_cmd = 'scp {} '.format(g_id_rsa_option)
    output, returncode = run(scp_cmd + ' {} {}@{}:{}'.format(
        local_file, g_args.ssh_user, g_new_instance_ip_address, destination),
                             hide_command=g_hide_command,
                             debug=g_args.debug)
    say(output)
Example #3
0
def textReact(message,irc):
	try:
		for c in texts:
			if c["reactTo"] == "sender":
				reactTo = common.senderFormat(message["from"],"nick")
			elif c["reactTo"] == "channel":
				if ommon.senderFormat(message["to"],"nick") != common.conf.read()["nick"]:
					reactTo = message["to"]
				else:
					reactTo = common.senderFormat(message["from"],"nick")
			if c["matchType"] == "equals" and message["message"].lower() == common.substitute(c["matchText"].lower(),message):
				if c["reactType"] == "say":
					common.say(reactTo,common.substitute(c["reactText"],message),irc)
					return True
				elif c["reactType"] == "me":
					common.me(reactTo,common.substitute(c["reactText"],message),irc)
					return True
			elif c["matchType"] == "contains" and message["message"].lower().find(common.substitute(c["matchText"].lower(),message)) != -1:
				if c["reactType"] == "say":
					common.say(reactTo,common.substitute(c["reactText"],message),irc)
					return True
				elif c["reactType"] == "me":
					common.me(reactTo,common.substitute(c["reactText"],message),irc)
					return True
		return False
	except:
		pass
Example #4
0
def textReact(message, irc):
    try:
        for c in texts:
            if c["reactTo"] == "sender":
                reactTo = common.senderFormat(message["from"], "nick")
            elif c["reactTo"] == "channel":
                if ommon.senderFormat(message["to"],
                                      "nick") != common.conf.read()["nick"]:
                    reactTo = message["to"]
                else:
                    reactTo = common.senderFormat(message["from"], "nick")
            if c["matchType"] == "equals" and message["message"].lower(
            ) == common.substitute(c["matchText"].lower(), message):
                if c["reactType"] == "say":
                    common.say(reactTo,
                               common.substitute(c["reactText"], message), irc)
                    return True
                elif c["reactType"] == "me":
                    common.me(reactTo,
                              common.substitute(c["reactText"], message), irc)
                    return True
            elif c["matchType"] == "contains" and message["message"].lower(
            ).find(common.substitute(c["matchText"].lower(), message)) != -1:
                if c["reactType"] == "say":
                    common.say(reactTo,
                               common.substitute(c["reactText"], message), irc)
                    return True
                elif c["reactType"] == "me":
                    common.me(reactTo,
                              common.substitute(c["reactText"], message), irc)
                    return True
        return False
    except:
        pass
def getExistingMasterInstance(current_master_ip=None):
    say('Making sure jenkins is not running on the master...', banner="*")
    # First make sure you can run a dummy command.
    cmd = '{} {}@{} \'echo hello\''.format(g_ssh_cmd, g_args.ssh_user,
                                           g_args.current_master_ip)
    run(cmd, hide_command=g_hide_command)
    say('Script was able to ssh onto master and run "echo hello world"...')

    # OK, not make sure jenkins is not running: Add an extra "-t", otherwise you will get:
    # sudo: sorry, you must have a tty to run sudo
    cmd = '{} -t {}@{} \'sudo service jenkins status\''.format(
        g_ssh_cmd, g_args.ssh_user, g_args.current_master_ip)
    output, returncode = run(cmd,
                             raise_on_failure=False,
                             hide_command=g_hide_command,
                             debug=g_args.debug)
    if 'jenkins' in output and 'is running...' in output:
        user_input = input(
            'Jenkins is running on the master.  Are you sure you want to continue? (y|n)'
        )
        if user_input != 'y':
            say('goodbye!')
            sys.exit(0)
    say('Getting instance from IP: ' + g_args.current_master_ip)
    output, returncode = run(
        'aws ec2 describe-instances --filters "Name=ip-address,Values=' +
        g_args.current_master_ip + '"',
        hide_command=g_hide_command,
        debug=g_args.debug)
    instance = json.loads(output)['Reservations'][0]['Instances'][0]
    say('Instance-id of existing Jenkins master: ' + instance['InstanceId'])
    return instance
def run_ssh(cmd, raise_on_failure=True):
    pre_cmd = '{} -t {}@{} '.format(g_ssh_cmd, g_args.ssh_user,
                                    g_new_instance_ip_address)
    output, returncode = run(pre_cmd + '\'{}\''.format(cmd),
                             hide_command=g_hide_command,
                             debug=g_args.debug,
                             raise_on_failure=raise_on_failure)
    say(output)
    return output, returncode
Example #7
0
def check_spot_instance_termination():
    while True:
        script_to_run = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         'check_spot_instance_termination.sh'))
        output, returncode = run(script_to_run)
        if returncode == 1:
            say('The instance is about to be terminated! Exiting script now!')
            os._exit(1)
        say(output)
        time.sleep(5)
Example #8
0
def mkCity(callingWidget, fileid, tabs):
    global cities
    if idExists(fileid, "c"):
        say("Existing fileid! Loading instead...")
    else:
        cities[fileid] = {}
        cities[fileid]["info"] = loadCity(fileid)
        cities[fileid]["changed"] = False
        cities[fileid]["cat"] = "c"
        saveThisC(callingWidget, fileid)
    displayCity(callingWidget, fileid, tabs)
Example #9
0
def mkState(callingWidget,fileid,tabs):
  global states
  if idExists(fileid,'s'):
    say("Existing fileid! Loading instead...")
  else:
    states[fileid] = {}
    states[fileid]['info'] = loadState(fileid)
    states[fileid]['changed'] = False
    states[fileid]['cat'] = 's'
    pushLoc(fileid)
    saveThisS(callingWidget,fileid)
  displayState(callingWidget,fileid,tabs)
Example #10
0
def amiExists(ami_id=None):
    cmd = 'aws ec2 describe-images --image-ids ' + ami_id
    output, returncode = run(cmd,
                             hide_command=g_hide_command,
                             debug=g_args.debug)
    j = json.loads(output)
    if len(j['Images']) == 0:
        say('AMI-ID not found: ' + ami_id)
        return False
    else:
        say('AMI-ID found: ' + ami_id)
        return True
Example #11
0
def mkPerson(callingWidget,fileid,tabs):
  global people
  if idExists(fileid,'p'):
    say("Existing fileid! Loading instead...")
  else:
    p = loadPerson(fileid)
    people[fileid] = {}
    people[fileid]['info'] = p[0]
    people[fileid]['relat'] = p[1]
    people[fileid]['changed'] = False
    people[fileid]['cat'] = 'p'
    saveThisP(callingWidget,fileid)
  displayPerson(callingWidget,fileid,tabs)
Example #12
0
def mkPlace(callingWidget,fileid,tabs):
  global places
  if idExists(fileid,'l'):
    say("Existing fileid! Loading instead...")
  else:
    L = loadPlace(fileid)
    places[fileid] = {}
    places[fileid]['info'] = L[0]
    places[fileid]['relat'] = L[1]
    places[fileid]['changed'] = False
    places[fileid]['cat'] = 'l'
    saveThisL(callingWidget,fileid)
  displayPlace(callingWidget,fileid,tabs)
Example #13
0
def react(t, irc):
    command, message = common.command(common.type(t))
    args = message['args']
    sender = common.senderFormat(message['from'], "nick")
    if command == None:
        return False
    if command.lower() != "weather":
        return False
    if len(args) == 0:
        location = getSavedData(sender)
    else:
        location = " ".join(args)
        putSavedData(sender, location)
    if location == False:
        if message["to"].split("!")[0] != common.conf.read()["nick"]:
            common.say(
                message['to'],
                "Sorry, I don't know where you live. Try \"{0}weather <location>\""
                .format(common.conf.read()['commands']['commandPrefix']), irc)
        else:
            common.say(
                common.senderFormat(message["from"], "nick"),
                "Sorry, I don't know where you live. Try \"{0}weather <location>\""
                .format(common.conf.read()['commands']['commandPrefix']), irc)
    else:
        if message["to"].split("!")[0] != common.conf.read()["nick"]:
            common.say(message['to'], stringFromLocation(location), irc)
        else:
            common.say(common.senderFormat(message["from"], "nick"),
                       stringFromLocation(location), irc)
Example #14
0
def attacheVolume(volume_id=None, instance_id=None, region=None):
    say('Attaching volume...', banner="*")
    cmd = 'aws ec2 attach-volume --volume-id ' + str(volume_id) + \
          ' --instance-id ' + str(instance_id) + \
          ' --device /dev/sdb'
    output, returncode = run(cmd,
                             hide_command=g_hide_command,
                             debug=g_args.debug)
    say(output)
    while True:
        cmd = 'aws ec2 describe-volumes --volume-ids ' + str(volume_id)
        output, returncode = run(cmd,
                                 hide_command=g_hide_command,
                                 debug=g_args.debug)
        state = json.loads(output)['Volumes'][0]['State']
        if state == 'in-use':
            say('Volume has been attached: ' + str(volume_id))
            break
        else:
            say('Current State: ' + str(state))
            time.sleep(15)
    # Re-describe the instance, since it now has a new volume:
    cmd = 'aws ec2 describe-instances --instance-ids {} --region {}'.format(
        instance_id, region)
    output, returncode = run(cmd,
                             hide_command=g_hide_command,
                             debug=g_args.debug)
    instance = json.loads(output)['Reservations'][0]['Instances'][0]
    return instance
Example #15
0
def kick_off_jobs(test_file):
    say('Kicking off all the workers...', banner='*', color='green')
    ret_jenkins_queue_jobs = []
    # Get all the tests from the tests.txt:
    all_tests = []
    with open(test_file, 'r') as fd:
        for test in fd.readlines():
            if test.strip() != '':
                all_tests.append(test.strip())
    say('num of tests  : {}'.format(len(all_tests)))
    say('These are the tests that set to be executed on this run:')
    for test in all_tests:
        say('test: {0}'.format(test))

    for test in all_tests:
        # For each test group, call a jenkins job to run them sequencially:
        params = {
            'GIT_HASH': args.git_hash,
            'UPSTREAM_BUILD_NUMBER': os.environ.get('BUILD_NUMBER', 'manual'),
            'TEST': test
        }
        # Put these jobs on the queue:
        r = build_job(host=args.jenkins_host,
                      build_name=args.worker_job,
                      params=params,
                      username=args.jenkins_username,
                      password=args.jenkins_password)
        ret_jenkins_queue_jobs.append(r)
    return ret_jenkins_queue_jobs
Example #16
0
def getPlacesIn(city):
  state = common.getInf(cities.get(city),["info","statefile"],None)
  if state.find(".xml") > -1: state = state.split('.')[0]
  if city.find(".xml") > -1: city = city.split('.')[0]
  if state:
    data = placeList.get(state)
    if data is not None:
      data = placeList[state].get(city)
      if data is not None:
        return data
      else:
        common.say("City %s not found in placeList" %city)
    else:
      common.say("State %s not found in placeList" % state)
  return {}
Example #17
0
def run(cmd):
    output = None
    returncode = None
    say('Running command: {}'.format(cmd))
    try:
        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT,
                             universal_newlines=True,
                             shell=True)
        output = p.communicate()[0]
        returncode = p.returncode
    except Exception:
        say('***Error in command: {0}'.format(cmd))
        say('Exception:----------------')
        say(traceback.format_exc())
        say('--------------------------')

    return output, returncode
Example #18
0
def createSnapshot(volume_id=None):
    say('Creating snapshot...', banner="*")
    cmd = 'aws ec2 create-snapshot --description jenkins-master-snapshot --volume-id ' + volume_id
    output, returncode = run(cmd,
                             hide_command=g_hide_command,
                             debug=g_args.debug)
    snapshot_id = json.loads(output)['SnapshotId']
    while True:
        cmd = 'aws ec2 describe-snapshots --snapshot-ids ' + str(snapshot_id)
        output, returncode = run(cmd,
                                 hide_command=g_hide_command,
                                 debug=g_args.debug)
        status = json.loads(output)['Snapshots'][0]['State']
        progress = json.loads(output)['Snapshots'][0]['Progress']
        if status == 'completed':
            say('Snapshot has been created!')
            break
        else:
            say('Current Status: ' + str(status) + '. Current Progress: ' +
                str(progress))
            time.sleep(15)
    cmd = 'aws ec2 create-tags --resources ' + str(
        snapshot_id) + ' --tags Key=Name,Value=jenkins-master-snapshot'
    output, returncode = run(cmd,
                             hide_command=g_hide_command,
                             debug=g_args.debug)
    return snapshot_id
Example #19
0
def commandReact(command,message,irc):
	arg = {}
	for i in range(0,len(message["args"])):
		arg.update({"arg"+str(i+1):message["args"][i]})
	if len(message["args"]) < 10:
		for i in range(len(message["args"]),10):
			arg.update({"arg"+str(i+1):""})
	for name in commands:
		c = commands[name]
		if c["reactTo"] == "sender":
			reactTo = common.senderFormat(message["from"],"nick")
		elif c["reactTo"] == "channel":
			if message["to"].split("!")[0] != common.conf.read()["nick"]:
				reactTo = message["to"]
			else:
				reactTo = common.senderFormat(message["from"],"nick")
		if command == name and c["reactType"] == "say":
			common.say(reactTo,common.substitute(c["reactText"],message,arg),irc)
			return True
		elif command == name and c["reactType"] == "me":
			common.me(reactTo,common.substitute(c["reactText"],message,arg),irc)
			return True
	return False
Example #20
0
def parseArgs():
    default_rpm = 'http://pkg.jenkins-ci.org/redhat-stable/jenkins-1.625.3-1.1.noarch.rpm'
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--ami_id', help='AMI-ID.', default='ami-8f5a4bee')
    parser.add_argument('--current-master-ip',
                        help='Public IP Address of existing Jenkins Master.')
    parser.add_argument('--id_rsa',
                        help='id_rsa file used to ssh onto the master.',
                        default=None)
    parser.add_argument('--key_pair_name',
                        help='AWS key name.',
                        default='jenkins.cloud')
    parser.add_argument('--ssh_user', help='ssh user.', default='ec2-user')
    parser.add_argument(
        '--target_env',
        help='The target env to create instance in. Usually "eod-us-west-2".',
        choices=g_env_map['environments'].keys(),
        default='eod-us-west-2')
    parser.add_argument('--volume_type',
                        help='The EBS volume type.',
                        choices=['gp2', 'standard'],
                        default='gp2')
    parser.add_argument(
        '--volume_size',
        help=
        'The EBS volume size in GB. If none specified, the size of the snapshot is used.',
        default=None)
    parser.add_argument('--instance_type',
                        help='The size of the instance.',
                        default='t2.medium')
    parser.add_argument('--jenkins_rpm',
                        help='The http location of the jenkins rpm.',
                        default=default_rpm)
    parser.add_argument('--owner_email',
                        help='The owner tag for the jenkins master',
                        default='*****@*****.**')
    parser.add_argument('--debug',
                        action='store_true',
                        help='Show debug information.')
    args = parser.parse_args()

    if args.current_master_ip is None and args.volume_size is None:
        say('You have not specified an existing jenkins master, so a EBS volme will be created for you.'
            )
        say('You must specify a volume size for this new volume.')
        say('Exiting with error...')
        sys.exit(1)
    return args
Example #21
0
def react(t,irc):
    command,message = common.command(common.type(t))
    args = message['args']
    sender = common.senderFormat(message['from'],"nick")
    if command == None:
        return False
    if command.lower() != "weather":
        return False
    if len(args) == 0:
        location = getSavedData(sender)
    else:
        location = " ".join(args)
        putSavedData(sender,location)
    if location == False:
        if message["to"].split("!")[0] != common.conf.read()["nick"]:
            common.say(message['to'],"Sorry, I don't know where you live. Try \"{0}weather <location>\"".format(common.conf.read()['commands']['commandPrefix'])  ,  irc)
        else:
            common.say(common.senderFormat(message["from"],"nick"),"Sorry, I don't know where you live. Try \"{0}weather <location>\"".format(common.conf.read()['commands']['commandPrefix']),irc)
    else:
        if message["to"].split("!")[0] != common.conf.read()["nick"]:
            common.say(message['to'],stringFromLocation(location),irc)
        else:
            common.say(common.senderFormat(message["from"],"nick"),stringFromLocation(location),irc)
Example #22
0
def findJenkinsVolume(instance=None):
    say('Finding data storage block device...', banner="*")
    for block_device in instance['BlockDeviceMappings']:
        if 'Ebs' in block_device.keys():
            output, returncode = run('aws ec2 describe-volumes --volume-ids ' +
                                     block_device['Ebs']['VolumeId'],
                                     hide_command=g_hide_command,
                                     debug=g_args.debug)
            j = json.loads(output)
            if 'Tags' in j['Volumes'][0].keys():
                for tag in j['Volumes'][0]['Tags']:
                    if tag['Key'] == 'Name' and tag[
                            'Value'] == 'jenkins-master-volume':
                        say('Found the volume that we want to create a snapshot from (has tag jenkins-master-volume): '
                            + block_device['Ebs']['VolumeId'] + '. Size:' +
                            str(json.loads(output)['Volumes'][0]['Size']))
                        return block_device
    say('***Error: Could not find master volume via the Name tag.')
    return None
Example #23
0
def createVolume(snapshot_id=None,
                 volume_type=None,
                 volume_size=None,
                 region=None,
                 az=None):
    say('Creating volume...', banner="*")
    snapshot_arg = ' --snapshot-id {}'.format(snapshot_id)
    if snapshot_id is None:
        snapshot_arg = ''

    volume_size = '' if volume_size is None else ' --size ' + volume_size
    cmd = 'aws ec2 create-volume --region ' + region + \
          ' --availability-zone ' + az + ' ' + \
          snapshot_arg + \
          ' --volume-type ' + volume_type + volume_size
    output, returncode = run(cmd,
                             hide_command=g_hide_command,
                             debug=g_args.debug)
    volume_id = json.loads(output)['VolumeId']
    size = json.loads(output)['Size']
    while True:
        cmd = 'aws ec2 describe-volumes --volume-ids ' + str(volume_id)
        output, returncode = run(cmd,
                                 hide_command=g_hide_command,
                                 debug=g_args.debug)
        state = json.loads(output)['Volumes'][0]['State']
        if state == 'available':
            say('Volume has been created: ' + str(volume_id))
            break
        else:
            say('Current State: ' + str(state))
            time.sleep(15)
    cmd = 'aws ec2 create-tags --resources ' + str(
        volume_id) + ' --tags Key=Name,Value=jenkins-master-volume'
    output, returncode = run(cmd,
                             hide_command=g_hide_command,
                             debug=g_args.debug)
    return volume_id, size
Example #24
0
def ingest(inCmd,
           inStr,
           mood=[],
           weight=[],
           isCmd=False,
           isMem=False,
           matches=[[], []]):
    from common import wordSim, processResponse, getResponse, say
    #from loadFile import load
    from determineFunction import findCMD, refineMatches
    from Fermi import substituteBiographicMemory

    if not (isCmd or isMem):
        matches = refineMatches(inCmd, inStr)
        matches = substituteBiographicMemory(matches, queryType='what is')

    if len(matches[0]) == 0 and not (isCmd or isMem):
        say(getResponse(findCMD("rephrase")),
            more=False,
            speak=setting("SPEAK"),
            moodUpdate=True)
        return False
    '''
	Algorithm:
		- load substance from list
		- record ingestion time
		- append to INGESTED list

	'''

    if isCmd:
        ingestionTime = time.time()

        taskProfile = "pow(2.0, -1.0*T*T/(900.0*900.0))"  # ~15 minute half life

        taskDetails = [[inCmd[0]], mood, weight, taskProfile]
        #print "appending: ", taskDetails

        GLOB['INGESTED'].append([taskDetails, ingestionTime, "COMMAND"])
        GLOB['MOOD'] = updateMood(GLOB['MOOD'], weight=[0] * GLOB['MOODDIM'])

        #print "AFTER CMD ADD"
        #print GLOB['MOOD']

        return  # no return value if adding a cmd mood modifier

    if isMem:
        #print "ADDING MEMORY MOOD"

        ingestionTime = time.time()

        memProfile = "pow(2.0, -1.0*T*T/(900.0*900.0))"  # ~15 minute half life

        memDetails = [[inStr], mood, weight, memProfile]
        #print "appending: ", taskDetails

        GLOB['INGESTED'].append([memDetails, ingestionTime, "MEMORY"])
        GLOB['MOOD'] = updateMood(GLOB['MOOD'], weight=[0] * GLOB['MOODDIM'])

        #print "AFTER CMD ADD"
        #print GLOB['MOOD']

        return  # no return value if adding a cmd mood modifier

    substances = load(SETS_DIR + "substances.txt", LPC=5)
    # line 0: name(s)
    # line 1: effect
    # line 2: weight
    # line 3: profile equations
    # line 4: response formats
    '''
	for matchStr in inCmd[1]:
		matchStr= matchStr.replace('juice','')
		inStr = inStr.replace(matchStr, '')
	'''

    # find top match

    maxMatch = 0
    topSubstance = []
    for substance in substances:
        for matchPhrase in substance[0]:
            matchScore = wordSim(matches[0][0], matchPhrase, useInScore=True)
            #print matchPhrase, inStr, matchScore
            if matchScore >= maxMatch:
                maxMatch = matchScore
                topSubstance = substance

    if setting('DEBUG'):
        print "INGESTION SCORE:", topSubstance[0], " - ", maxMatch

    # topSubstance[4]:

    #replacements = [topSubstance[0][randint(0,len(topSubstance[0])-1)]]
    replacements = topSubstance[0][randint(0,
                                           len(topSubstance[0]) -
                                           1)]  #matches[0][0] #
    #rStr = processResponse(getResponse(inCmd), replacements)
    responseForm = topSubstance[4][randint(0, len(topSubstance[4]) - 1)]
    rStr = processResponse(responseForm, [replacements])

    say(rStr, more=False, speak=setting("SPEAK"))

    # now modify mood accordingly
    ingestionTime = time.time()

    #print "appending: ", topSubstance

    GLOB['INGESTED'].append([topSubstance, ingestionTime, "SUBSTANCE"])

    #print "BEFORE UPDATE"
    #print GLOB['MOOD']

    GLOB['MOOD'] = updateMood(GLOB['MOOD'], weight=[0] * GLOB['MOODDIM'])

    #print "AFTER SUBSTANCE ADD"
    #print GLOB['MOOD']

    return [topSubstance[0][0], True]
Example #25
0
        say('--------------------------')

    return output, returncode


def check_spot_instance_termination():
    while True:
        script_to_run = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         'check_spot_instance_termination.sh'))
        output, returncode = run(script_to_run)
        if returncode == 1:
            say('The instance is about to be terminated! Exiting script now!')
            os._exit(1)
        say(output)
        time.sleep(5)


if __name__ == '__main__':
    args = parseArgs()

    # Run thread that checks if spot instance is about to be destroyed:
    thread = threading.Thread(target=check_spot_instance_termination)
    thread.daemon = True
    thread.start()

    # Run all the tests:
    output, returncode = run(os.environ.get('TEST', 'echo "no tests!"'))
    say('OUTPUT: \n{}'.format(output))
    sys.exit(returncode)
Example #26
0
if __name__ == "__main__":
    # Parse the command line args:
    g_args = parseArgs()

    # Debug or no Debug:
    g_hide_command = False if g_args.debug is True else True

    # Is this a new master or clone from existing master:
    b_new_instance = True if g_args.current_master_ip is None else False
    g_new_instance_ip_address = None

    # Setup general ssh command syntax:
    if g_args.id_rsa is not None:
        if not os.path.exists(g_args.id_rsa):
            say('***Error: File does not exist: {}'.g_args.id_rsa)
            sys.exit(1)
    g_id_rsa_option = '' if g_args.id_rsa is None else '-i {}'.format(
        g_args.id_rsa)
    g_ssh_cmd = (
        'ssh {} -o ControlMaster=no -o ConnectTimeout=30 -t -n '
        '-o PreferredAuthentications=publickey -o StrictHostKeyChecking=no '
        '-o UserKnownHostsFile=/dev/null').format(g_id_rsa_option)

    if amiExists(ami_id=g_args.ami_id) is False:
        say('***Error: You have to pass in an AMI that exists.')
        sys.exit(1)

    snapshot_id = None
    subnet_id = random.choice(
        g_env_map['environments'][g_args.target_env]['vpcsubnet'])['id']
Example #27
0
def moodReport(inCmd, inStr, matches=[[], []]):
    from common import say, getResponse
    from Fermi import stateSummary
    from satisfactionMaximization import IV

    reportType = "short"
    if "report" in inStr:
        reportType = "full"

    PREVMOOD = GLOB['PREVMOOD']
    MOOD = GLOB['MOOD']
    INGESTED = GLOB['INGESTED']

    if reportType == "short":
        #mVec = copy.deepcopy(MOOD)
        #mVec = fullMoodVec(mVec)

        Fm = fullMoodVec(MOOD, pronoun=True)  # weight vector
        Fm.sort(key=lambda tup: tup[1])
        Fm.reverse()

        #curFace = getFace(MOOD)
        #rStr = "I am feeling "+curFace[2]+"."

        rStr = "I am feeling " + Fm[0][0]
        if Fm[0][0] >= 0:
            rStr += ", but"
        else:
            rStr += ", and"

        #print "HERE"

        # sort by weight
        Fw = fullMoodVec(IV(), colloquial=True)  # weight vector
        Fw.sort(key=lambda tup: tup[1])
        Fw.reverse()

        topNeed = Fw[0]
        if topNeed[1] >= 0.85:
            rStr += " I am badly in need of some " + topNeed[0] + '.'
        elif topNeed[1] >= 0.5:
            rStr += " I am in need of some " + topNeed[0] + '.'
        elif topNeed[1] >= 0.25:
            rStr += " I could use some " + topNeed[0] + '.'
        else:
            rStr += " I wouldn't mind some " + topNeed[0] + '.'

        say(rStr, more=False, speak=setting("SPEAK"), location="history")

        #topThought = m.getTopSentence(QV, ["", GLOB['MOOD']])
        #print k.sf(topThought[1], 3)
        #say('*'+topThought[0]+'*', more=False, speak=setting("SPEAK"), moodUpdate=True)

    else:

        # want to get previous mood before AI talks about mood report
        prevFace = getFace(PREVMOOD)

        say(getResponse(inCmd), more=False, speak=setting("SPEAK"))

        curFace = getFace(MOOD)

        SMood, iWeights = ingestionMood(moodType="SUBSTANCE")
        imVec = [SMood[i] * iWeights[i] for i in range(GLOB['MOODDIM'])]
        iFace = getFace(SMood)

        T = timeFactor()

        print
        print " Current mood:", curFace[2]
        print "     Emoticon:", curFace[0]
        #print "\n     %s" % ''.join('%s'%MOOD)
        stateSummary()

        print
        print "Previous mood:", prevFace[2]
        print "     Emoticon:", prevFace[0]
        #print "\n     %s" % ''.join('%s'%PREVMOOD)
        stateSummary(PREVMOOD)

        print
        print "Mood from ingestions"
        print "     Emoticon:", iFace[0]
        #print "\n     %s" % ''.join('%s'%imVec)
        stateSummary(imVec)

        print
        print "Mood from time of day"
        print "     Emoticon:", getFace(T)[0]
        print "      Arousal: %.2f" % T[1]
    return True
Example #28
0
def help(args, caller, irc):
    print("Help is running")
    print("help(" + str(args) + "," + str(caller) + "," + str(irc) + ")")
    if len(args) <= 1:
        common.say(common.senderFormat(caller, "nick"), helpText["help"], irc)
    elif args[1] == "":
        print("saying helptext")
        common.say(common.senderFormat(caller, "nick"), helpText["help"], irc)
        print("said helptext")
    elif args[1][0] == "a":
        common.say(common.senderFormat(caller, "nick"), helpText["add"], irc)
    elif args[1][0] == "r":
        common.say(common.senderFormat(caller, "nick"), helpText["remove"],
                   irc)
    elif args[1][0] == "e":
        common.say(common.senderFormat(caller, "nick"), helpText["edit"], irc)
    elif args[1][0] == "l":
        common.say(common.senderFormat(caller, "nick"), helpText["list"], irc)
    else:
        common.say(common.senderFormat(caller, "nick"), "Yerwhat!?", irc)
Example #29
0
def setTerminationPolicy(instance=None, region=None):
    # Before terminating, make sure all block devices are set to DeleteOnTermination is true:
    for block_device in instance['BlockDeviceMappings']:
        say('------------')
        say(block_device)
        if 'Ebs' in block_device.keys():
            if block_device['Ebs']['DeleteOnTermination'] is False:
                # Flip the bit to true:
                device_name = block_device['DeviceName']
                cmd_modify = 'aws ec2 modify-instance-attribute' + \
                             ' --region ' + region + \
                             ' --instance-id ' + str(instance['InstanceId']) + \
                             ' --block-device-mappings ' + \
                             '\'[{"DeviceName": "' + device_name + '","Ebs":{"DeleteOnTermination":true}}]\''
                output, returncode = run(cmd_modify,
                                         hide_command=True,
                                         retry_count=3)
                # Wait for it to stick:
                bHasStuck = False
                say('Waiting for termination policy to stick...')
                for i in range(30):
                    cmd = 'aws ec2 describe-instance-attribute --instance-id {}' \
                          ' --attribute blockDeviceMapping --region {}'.format(instance['InstanceId'], region)
                    output, returncode = run(cmd,
                                             hide_command=True,
                                             retry_count=3)
                    # We have to loop (again) to find the block device that we just set :(
                    for bd in json.loads(output)['BlockDeviceMappings']:
                        if bd['DeviceName'] == device_name:
                            if bd['Ebs']['DeleteOnTermination'] is True:
                                bHasStuck = True
                                break
                    if bHasStuck is True:
                        say('DeleteOnTermination has stuck!')
                        break
                    else:
                        say('Block device DeleteOnTermination has not stuck yet. Sleeping for 2 seconds...'
                            )
                        time.sleep(2)
                if bHasStuck is False:
                    say('***Error: We set the launch perm, but it did not stick. Error!'
                        )
                    sys.exit(1)
    say('All block devices on instance, ' + str(instance['InstanceId']) +
        ', are set to terminate on deletion.')
Example #30
0
def help(args,caller,irc):
	print("Help is running")
	print("help("+str(args)+","+str(caller)+","+str(irc)+")")
	if len(args) <= 1:
		common.say(common.senderFormat(caller,"nick"),helpText["help"],irc)
	elif args[1] == "":
		print("saying helptext")
		common.say(common.senderFormat(caller,"nick"),helpText["help"],irc)
		print("said helptext")
	elif args[1][0] == "a":
		common.say(common.senderFormat(caller,"nick"),helpText["add"],irc)
	elif args[1][0] == "r":
		common.say(common.senderFormat(caller,"nick"),helpText["remove"],irc)
	elif args[1][0] == "e":
		common.say(common.senderFormat(caller,"nick"),helpText["edit"],irc)
	elif args[1][0] == "l":
		common.say(common.senderFormat(caller,"nick"),helpText["list"],irc)
	else:
		common.say(common.senderFormat(caller,"nick"),"Yerwhat!?",irc)
Example #31
0
def add(args, caller, irc):
    if len(args) < 6:
        common.say(
            common.senderFormat(caller, "nick"),
            "Oops, try sending the right number of arguments (see \"{cp}sr help add\" if you're having trouble)"
            .replace("{cp}",
                     common.conf.read()["commands"]["commandPrefix"]), irc)
    elif args[1][0].lower() == "c":  #command
        if len(args) > 6:
            args[5] = " ".join(args[5:])
            args = args[:6]
        if len(args) == 6:
            if args[3][0].lower() in ("m", "s") and args[4][0].lower() in (
                    "c", "s"):  #me,say channel,sender
                name = args[2]
                if args[3][0].lower() == "m":
                    args[3] = "me"
                elif args[3][0].lower() == "s":
                    args[3] = "say"
                if args[4][0].lower() == "c":
                    args[4] = "channel"
                elif args[4][0].lower() == "s":
                    args[4] = "sender"
                command = {
                    "reactType": args[3],
                    "reactTo": args[4],
                    "reactText": args[5]
                }
                # DO THIS
                cfg = common.persistence.confLoad("simpleResponse",
                                                  defaultConf)
                try:
                    texts = cfg["texts"]
                    commands = cfg["commands"]
                    helpText = cfg["helpText"]
                except:
                    common.say(common.senderFormat(caller, "nick"),
                               "Something done gone wrong :(", irc)
                commands.update({name: command})
                common.persistence.confSave("simpleResponse", {
                    "commands": commands,
                    "texts": texts,
                    "helpText": helpText
                })
                common.say(
                    common.senderFormat(caller, "nick"),
                    "Hoorah! command \"{cp}{0}\" will be responded to by {1} with \"/{2} {3}\""
                    .replace("{cp}",
                             common.conf.read()["commands"]
                             ["commandPrefix"]).format(args[2], args[4],
                                                       args[3], args[5]), irc)
            else:
                common.say(
                    common.senderFormat(caller, "nick"),
                    "Oops, something went wrong. Check all your arguments are valid. (see \"{cp}sr help add\" if you're having trouble)"
                    .replace("{cp}",
                             common.conf.read()["commands"]["commandPrefix"]),
                    irc)
        else:
            common.say(
                common.senderFormat(caller, "nick"),
                "Oops, try sending the right number of arguments (see \"{cp}sr help add\" if you're having trouble)"
                .replace("{cp}",
                         common.conf.read()["commands"]["commandPrefix"]), irc)
    elif args[1][0].lower() == "t":  #text
        if len(args) > 7:
            args[6] = " ".join(args[6:])
            args = args[:7]
        if len(args) == 7:
            if args[2][0].lower() in ("e", "c") and args[4][0].lower() in (
                    "m", "s") and args[5][0].lower() in (
                        "c", "s"):  #equals,contains me,say channel,sender
                if args[4][0].lower() == "m":
                    args[4] = "me"
                elif args[4][0].lower() == "s":
                    args[4] = "say"
                if args[5][0].lower() == "c":
                    args[5] = "channel"
                elif args[5][0].lower() == "s":
                    args[5] = "sender"
                if args[2][0].lower() == "e":
                    args[2] = "equals"
                elif args[2][0].lower() == "c":
                    args[2] = "contains"
                else:
                    common.say(common.senderFormat(caller, "nick"),
                               "Yerwhat!?", irc)
                command = {
                    "matchType": args[2],
                    "matchText": args[3],
                    "reactType": args[4],
                    "reactTo": args[5],
                    "reactText": args[6]
                }
                cfg = common.persistence.confLoad("simpleResponse",
                                                  defaultConf)
                try:
                    texts = cfg["texts"]
                    commands = cfg["commands"]
                    helpText = cfg["helpText"]
                except:
                    common.say(common.senderFormat(caller, "nick"),
                               "Something done gone wrong :(", irc)
                texts += [command]
                cfg.update({
                    "texts": texts,
                })
                common.persistence.confSave("simpleResponse", cfg)
                common.say(
                    common.senderFormat(caller, "nick"),
                    "Hoorah! text that {0} \"{1}\" will be responded to by {2} with \"/{3} {4}\""
                    .format(args[2], args[3], args[5], args[4], args[6]), irc)
            else:
                common.say(
                    common.senderFormat(caller, "nick"),
                    "Oops, something went wrong. Check all your arguments are valid. (see \"!sr help add\" if you're having trouble)",
                    irc)
        else:
            common.say(
                common.senderFormat(caller, "nick"),
                "Oops, try sending the right number of arguments (see \"!sr help add\" if you're having trouble)",
                irc)
    else:
        common.say(common.senderFormat(caller, "nick"), "Yerwhat!?", irc)
Example #32
0
def moodReport(inCmd, inStr, matches=[[],[]]):
	from common import say, getResponse
	from Fermi import stateSummary
	from satisfactionMaximization import IV

	reportType="short"
	if "report" in inStr:
		reportType = "full"


	PREVMOOD = GLOB['PREVMOOD']
	MOOD = GLOB['MOOD']
	INGESTED = GLOB['INGESTED']

	if reportType == "short":
		#mVec = copy.deepcopy(MOOD)
		#mVec = fullMoodVec(mVec)
		

		Fm = fullMoodVec(MOOD,pronoun=True) # weight vector
		Fm.sort(key=lambda tup: tup[1])
		Fm.reverse()

		#curFace = getFace(MOOD)
		#rStr = "I am feeling "+curFace[2]+"."
		
		rStr = "I am feeling "+Fm[0][0]
		if Fm[0][0] >= 0:
			rStr += ", but"
		else:
			rStr += ", and"

		#print "HERE"


		# sort by weight
		Fw = fullMoodVec(IV(),colloquial=True) # weight vector
		Fw.sort(key=lambda tup: tup[1])
		Fw.reverse()

		topNeed = Fw[0]
		if topNeed[1] >= 0.85:
			rStr += " I am badly in need of some "+topNeed[0]+'.'
		elif topNeed[1] >= 0.5:
			rStr += " I am in need of some "+topNeed[0]+'.'
		elif topNeed[1] >= 0.25:
			rStr += " I could use some "+topNeed[0]+'.'
		else:
			rStr += " I wouldn't mind some "+topNeed[0]+'.'


		say(rStr, more=False, speak=setting("SPEAK"), location="history")
		
		#topThought = m.getTopSentence(QV, ["", GLOB['MOOD']])
		#print k.sf(topThought[1], 3)
		#say('*'+topThought[0]+'*', more=False, speak=setting("SPEAK"), moodUpdate=True)


	else:

		# want to get previous mood before AI talks about mood report
		prevFace = getFace(PREVMOOD)

		say(getResponse(inCmd), more=False, speak=setting("SPEAK"))

		curFace = getFace(MOOD)
		
		SMood, iWeights = ingestionMood(moodType="SUBSTANCE")
		imVec = [SMood[i]*iWeights[i] for i in range(GLOB['MOODDIM'])]
		iFace = getFace(SMood)
		
		T = timeFactor()

		print
		print " Current mood:", curFace[2] 
		print "     Emoticon:", curFace[0]
		#print "\n     %s" % ''.join('%s'%MOOD)
		stateSummary()

		print
		print "Previous mood:", prevFace[2]
		print "     Emoticon:", prevFace[0]
		#print "\n     %s" % ''.join('%s'%PREVMOOD)
		stateSummary(PREVMOOD)

		print
		print "Mood from ingestions"
		print "     Emoticon:", iFace[0]
		#print "\n     %s" % ''.join('%s'%imVec)
		stateSummary(imVec)

		print
		print "Mood from time of day"
		print "     Emoticon:", getFace(T)[0]
		print "      Arousal: %.2f" % T[1]
	return True
Example #33
0
def deltaMoodQuery(inCmd=[], inStr="", matches=[[],[]], fromAuto=False):
	from common import say
	from random import random
	# how did that make you feel?
	# -> diff between prevmood and mood
	#print "PREV MOOD:", GLOB['CMDHIST'][len(GLOB['CMDHIST'])]
	#print "CUR MOOD:", GLOB['MOOD']

	cNum = len(GLOB['CMDHIST'])

	saidSomething = False

	if cNum >= 3:

		#print "HERE"

		oldMood = GLOB['CMDHIST'][cNum-2][3]
		newMood = GLOB['CMDHIST'][cNum-1][3]

		

		deltaMood = [newMood[i] - oldMood[i] for i in range(GLOB['MOODDIM'])]

		maxDelta = max([abs(item) for item in deltaMood])
		
		# only tell mood with certain probability if fromAuto
		#if setting('VERBOSE_MOOD')*maxDelta < random() and fromAuto:
		deltaThreshold = 2.0*(1.0 - setting('VERBOSE_MOOD'))
		if maxDelta < deltaThreshold and fromAuto:
			#print "maxDelta:", maxDelta
			return False #True

		
		feelings=[]
		for i in range(len(deltaMood)):
			item = deltaMood[i]
			if abs(item) >= 0.75:
				feelings.append("a lot more "+getStatePronoun(i, positive=item>0))
			elif abs(item) >= 0.5:
				feelings.append(getStatePronoun(i, positive=item>0))
			elif abs(item) >= 0.3:
				feelings.append("a little more "+getStatePronoun(i, positive=item>0))

		if len(feelings) == 0:
			if not fromAuto:
				say("That did not really affect me.", more=False, speak=setting("SPEAK"))
				saidSomething= True
		else:
			if not fromAuto:
				say("I am feeling "+listize(feelings)+'.', more=False, speak=setting("SPEAK"))
			else:
				#tkTopClear()
				tkTopCat("*That made me feel "+listize(feelings)+'.*')
			saidSomething = True
		'''
		elif len(feelings) == 1:
			say("I am feeling "+feelings[0]+'.', more=False, speak=setting("SPEAK"))
		elif len(feelings) == 2:
			say("I am feeling "+' and '.join(feelings)+'.', more=False, speak=setting("SPEAK"))
		else:
			say("I am feeling "+', '.join(feelings)+'.', more=False, speak=setting("SPEAK"))
		'''


	else:
		if not fromAuto:
			say("I'm not sure.", more=False, speak=setting("SPEAK"))
			saidSomething = True


	return saidSomething #True
Example #34
0
def configureInstance(volume_size=None,
                      default_rpm=None,
                      is_new_instance=True):
    say('Running ssh commands to configure box...', banner="*")
    run_ssh('sudo mkdir -p /var/build')
    while True:
        say('Waiting for {}G partition to be availabe by the OS...'.format(
            volume_size))
        # -i option in lsblk is "ascii output"
        output, returncode = run_ssh(
            'sudo lsblk -i | grep {}G | grep -v grep'.format(volume_size),
            raise_on_failure=False)
        if returncode == 0:
            say('{}G volume is now availabe by the OS!'.format(volume_size))
            run_ssh('sudo lsblk -i')
            break
        time.sleep(5)

    run_ssh('sudo file -s /dev/xvdb')
    if is_new_instance is True:
        say('Brand new master. Formating EBS drive...')
        # Creating brand new jenkin master, not cloned from an existing one.
        # Format existing volume:
        run_ssh('sudo mkfs -F -t ext4 /dev/xvdb')

    run_ssh('sudo mount /dev/xvdb /var/build')
    run_ssh('sudo mkdir -p /var/build/jenkins')

    # Modify /etc/fstab:
    run_ssh('echo "#!/bin/sh" > /tmp/fstab.sh')
    run_ssh(
        'echo "echo "/dev/xvdb /var/build ext4 defaults,nofail 0 2" >> /etc/fstab" >> /tmp/fstab.sh'
    )
    run_ssh('sudo chmod +x /tmp/fstab.sh')
    run_ssh('sudo /tmp/fstab.sh')

    # Make sure /etc/fstab is OK:
    run_ssh('sudo mount -a')

    # Install some packages:
    run_ssh('sudo yum -y install git')
    run_ssh('sudo yum -y install java-1.8.0-openjdk-devel')
    run_ssh(
        'sudo alternatives --set java /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java'
    )

    # Install Jenkins:
    run_ssh('cd /tmp && wget --quiet {}'.format(default_rpm))
    run_ssh('cd /tmp && sudo yum -y install {}'.format(default_rpm))

    if is_new_instance is True:
        say('Brand new instance must have /var/build/jenkins/etc.sysconfig.jenkins...'
            )
        run_ssh(
            'sudo mv /etc/sysconfig/jenkins /var/build/jenkins/etc.sysconfig.jenkins'
        )

    run_ssh('sudo rm -rf /etc/sysconfig/jenkins')
    run_ssh(
        'sudo ln -s /var/build/jenkins/etc.sysconfig.jenkins /etc/sysconfig/jenkins'
    )
    run_ssh('sudo rm -rf /var/lib/jenkins')
    run_ssh('sudo ln -s /var/build/jenkins/ /var/lib/jenkins')

    # Install pip and virtualenv:
    run_ssh('sudo wget --quiet https://bootstrap.pypa.io/get-pip.py')
    run_ssh('sudo python get-pip.py')
    run_ssh('sudo pip install virtualenv')
    run_ssh('sudo pip install termcolor')
    run_ssh('sudo pip install requests==2.18.4')

    # Install logrotate:
    run_scp(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__), 'logrotate_jenkins')),
        '/tmp')
    run_ssh('sudo mv /tmp/logrotate_jenkins /etc/logrotate.d/')
    run_ssh('sudo chown root:root /etc/logrotate.d/logrotate_jenkins')

    # Install and run nginx:
    run_scp(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__), 'install_nginx.sh')),
        '/tmp')
    run_scp(
        os.path.abspath(os.path.join(os.path.dirname(__file__), 'nginx.conf')),
        '/tmp')
    run_scp(
        os.path.abspath(
            os.path.join(os.path.dirname(__file__), 'etc.init.d.nginx')),
        '/tmp')
    run_ssh('sudo mv /tmp/nginx.conf /var/build/jenkins/')
    run_ssh('sudo mv /tmp/etc.init.d.nginx /var/build/jenkins/')
    run_ssh('sudo bash /tmp/install_nginx.sh')

    if is_new_instance is True:
        run_ssh('sudo chown -R jenkins:jenkins /var/build/jenkins')
        say("This is a brand new installation of jenkins.  Please see /var/lib/jenkins/secrets/initialAdminPassword for the initial password!"
            )
        say("And start jenkins with: sudo service jenkins start.  It will be running on port 8080"
            )
        say("Your next steps are to install a cert and run jenkins on port 443."
            )
Example #35
0
def deltaMoodQuery(inCmd=[], inStr="", matches=[[], []], fromAuto=False):
    from common import say
    from random import random
    # how did that make you feel?
    # -> diff between prevmood and mood
    #print "PREV MOOD:", GLOB['CMDHIST'][len(GLOB['CMDHIST'])]
    #print "CUR MOOD:", GLOB['MOOD']

    cNum = len(GLOB['CMDHIST'])

    saidSomething = False

    if cNum >= 3:

        #print "HERE"

        oldMood = GLOB['CMDHIST'][cNum - 2][3]
        newMood = GLOB['CMDHIST'][cNum - 1][3]

        deltaMood = [newMood[i] - oldMood[i] for i in range(GLOB['MOODDIM'])]

        maxDelta = max([abs(item) for item in deltaMood])

        # only tell mood with certain probability if fromAuto
        #if setting('VERBOSE_MOOD')*maxDelta < random() and fromAuto:
        deltaThreshold = 2.0 * (1.0 - setting('VERBOSE_MOOD'))
        if maxDelta < deltaThreshold and fromAuto:
            #print "maxDelta:", maxDelta
            return False  #True

        feelings = []
        for i in range(len(deltaMood)):
            item = deltaMood[i]
            if abs(item) >= 0.75:
                feelings.append("a lot more " +
                                getStatePronoun(i, positive=item > 0))
            elif abs(item) >= 0.5:
                feelings.append(getStatePronoun(i, positive=item > 0))
            elif abs(item) >= 0.3:
                feelings.append("a little more " +
                                getStatePronoun(i, positive=item > 0))

        if len(feelings) == 0:
            if not fromAuto:
                say("That did not really affect me.",
                    more=False,
                    speak=setting("SPEAK"))
                saidSomething = True
        else:
            if not fromAuto:
                say("I am feeling " + listize(feelings) + '.',
                    more=False,
                    speak=setting("SPEAK"))
            else:
                #tkTopClear()
                tkTopCat("*That made me feel " + listize(feelings) + '.*')
            saidSomething = True
        '''
		elif len(feelings) == 1:
			say("I am feeling "+feelings[0]+'.', more=False, speak=setting("SPEAK"))
		elif len(feelings) == 2:
			say("I am feeling "+' and '.join(feelings)+'.', more=False, speak=setting("SPEAK"))
		else:
			say("I am feeling "+', '.join(feelings)+'.', more=False, speak=setting("SPEAK"))
		'''

    else:
        if not fromAuto:
            say("I'm not sure.", more=False, speak=setting("SPEAK"))
            saidSomething = True

    return saidSomething  #True
Example #36
0
def driver(test_file):
    # Kick off all jenkins jobs:
    jenkins_queue_jobs = kick_off_jobs(test_file)
    say('Waiting for all worker jobs to get off the jenkins queue...',
        banner='*',
        color='green')
    builds = []
    for q in jenkins_queue_jobs:
        while True:
            try:
                q.poll()
                builds.append(q.get_build())
                break
            except NotBuiltYet:
                say('still on the queue: {0}'.format(q))
                time.sleep(10)
                continue
            except requests.exceptions.HTTPError as ex:
                # Edge case where queue item is off the queue
                # and has been deleted by Jenkins
                if ex.response.status_code == 404:
                    say('breaking out of loop for this item on the queue...')
                    break

    say('All jobs off the queue! Waiting for all jobs to finish...',
        banner='*',
        color='green')
    ret_code = 0
    master_results = []
    while len(builds) > 0:
        say('*' * 75)
        for b in builds:
            b.poll()
            if b.is_running() is True:
                say('Still building: {0} url: {1}'.format(b.name, b.baseurl))
                isBuilding = True
                time.sleep(10)
            else:
                # It takes one more poll to get the results:
                b.poll()
                say('Build Done: {0} status: {1}'.format(
                    b.baseurl, b.get_status()))
                # Regardless of what happened, the worker is done, so
                # take it off the list
                if b.get_status() != 'SUCCESS':
                    ret_code += 1
                master_results.append(b)
                builds.remove(b)

    say('Results', banner='*', color='green')
    for build in master_results:
        say('Status: {0}, URL: {1}'.format(build.get_status(), build.baseurl))
    say('All done!')
    return ret_code
Example #37
0
def add(args,caller,irc):
		if len(args) < 6:
			common.say(common.senderFormat(caller,"nick"),"Oops, try sending the right number of arguments (see \"{cp}sr help add\" if you're having trouble)".replace("{cp}",common.conf.read()["commands"]["commandPrefix"]),irc)
		elif args[1][0].lower() == "c": #command
			if len(args) > 6:
				args[5] = " ".join(args[5:])
				args = args[:6]
			if len(args) == 6:
				if args[3][0].lower() in ("m","s") and args[4][0].lower() in ("c","s"): #me,say channel,sender
					name = args[2]
					if args[3][0].lower() == "m":
						args[3] = "me"
					elif args[3][0].lower() == "s":
						args[3] = "say"
					if args[4][0].lower() == "c":
						args[4] = "channel"
					elif args[4][0].lower() == "s":
						args[4] = "sender"
					command = {"reactType":args[3],"reactTo":args[4],"reactText":args[5]}
					# DO THIS
					cfg = common.persistence.confLoad("simpleResponse",defaultConf)
					try:
						texts = cfg["texts"]
						commands = cfg["commands"]
						helpText = cfg["helpText"]
					except:
						common.say(common.senderFormat(caller,"nick"),"Something done gone wrong :(",irc)
					commands.update({name:command})
					common.persistence.confSave("simpleResponse",{"commands":commands,"texts":texts,"helpText":helpText})
					common.say(common.senderFormat(caller,"nick"),"Hoorah! command \"{cp}{0}\" will be responded to by {1} with \"/{2} {3}\"".replace("{cp}",common.conf.read()["commands"]["commandPrefix"]).format(args[2],args[4],args[3],args[5]),irc)
				else:
					common.say(common.senderFormat(caller,"nick"),"Oops, something went wrong. Check all your arguments are valid. (see \"{cp}sr help add\" if you're having trouble)".replace("{cp}",common.conf.read()["commands"]["commandPrefix"]),irc)
			else:
				common.say(common.senderFormat(caller,"nick"),"Oops, try sending the right number of arguments (see \"{cp}sr help add\" if you're having trouble)".replace("{cp}",common.conf.read()["commands"]["commandPrefix"]),irc)
		elif args[1][0].lower() == "t": #text
			if len(args) > 7:
				args[6] = " ".join(args[6:])
				args = args[:7]
			if len(args) == 7:
				if args[2][0].lower() in ("e","c") and args[4][0].lower() in ("m","s") and args[5][0].lower() in ("c","s"): #equals,contains me,say channel,sender
					if args[4][0].lower() == "m":
						args[4] = "me"
					elif args[4][0].lower() == "s":
						args[4] = "say"
					if args[5][0].lower() == "c":
						args[5] = "channel"
					elif args[5][0].lower() == "s":
						args[5] = "sender"
					if args[2][0].lower() == "e":
						args[2] = "equals"
					elif args[2][0].lower() == "c":
						args[2] = "contains"
					else:
						common.say(common.senderFormat(caller,"nick"),"Yerwhat!?",irc)
					command = {"matchType":args[2],"matchText":args[3],"reactType":args[4],"reactTo":args[5],"reactText":args[6]}
					cfg = common.persistence.confLoad("simpleResponse",defaultConf)
					try:
						texts = cfg["texts"]
						commands = cfg["commands"]
						helpText = cfg["helpText"]
					except:
						common.say(common.senderFormat(caller,"nick"),"Something done gone wrong :(",irc)
					texts += [command]
					cfg.update({"texts":texts,})
					common.persistence.confSave("simpleResponse",cfg)
					common.say(common.senderFormat(caller,"nick"),"Hoorah! text that {0} \"{1}\" will be responded to by {2} with \"/{3} {4}\"".format(args[2],args[3],args[5],args[4],args[6]),irc)
				else:
					common.say(common.senderFormat(caller,"nick"),"Oops, something went wrong. Check all your arguments are valid. (see \"!sr help add\" if you're having trouble)",irc)
			else:
				common.say(common.senderFormat(caller,"nick"),"Oops, try sending the right number of arguments (see \"!sr help add\" if you're having trouble)",irc)
		else:
			common.say(common.senderFormat(caller,"nick"),"Yerwhat!?",irc)
Example #38
0
def ingest(inCmd, inStr, mood=[], weight=[], isCmd=False, isMem=False, matches=[[],[]]):
	from common import wordSim, processResponse, getResponse, say
	#from loadFile import load
	from determineFunction import findCMD, refineMatches
	from Fermi import substituteBiographicMemory

	if not (isCmd or isMem):
		matches = refineMatches(inCmd, inStr)
		matches = substituteBiographicMemory(matches, queryType='what is')

	if len(matches[0]) ==0 and not (isCmd or isMem):
		say(getResponse(findCMD("rephrase")), more=False, speak=setting("SPEAK"), moodUpdate=True)
		return False

	'''
	Algorithm:
		- load substance from list
		- record ingestion time
		- append to INGESTED list

	'''

	if isCmd:
		ingestionTime = time.time()
		
		taskProfile="pow(2.0, -1.0*T*T/(900.0*900.0))" # ~15 minute half life
		
		taskDetails = [[inCmd[0]], mood, weight, taskProfile]
		#print "appending: ", taskDetails

		GLOB['INGESTED'].append([taskDetails, ingestionTime, "COMMAND"])
		GLOB['MOOD']=updateMood(GLOB['MOOD'], weight=[0]*GLOB['MOODDIM'])
		
		#print "AFTER CMD ADD"
		#print GLOB['MOOD']

		return # no return value if adding a cmd mood modifier

	if isMem:
		#print "ADDING MEMORY MOOD"

		ingestionTime = time.time()
		
		memProfile="pow(2.0, -1.0*T*T/(900.0*900.0))" # ~15 minute half life
		


		memDetails = [[inStr], mood, weight, memProfile]
		#print "appending: ", taskDetails

		GLOB['INGESTED'].append([memDetails, ingestionTime, "MEMORY"])
		GLOB['MOOD']=updateMood(GLOB['MOOD'], weight=[0]*GLOB['MOODDIM'])
		
		#print "AFTER CMD ADD"
		#print GLOB['MOOD']

		return # no return value if adding a cmd mood modifier




	substances = load(SETS_DIR+"substances.txt", LPC=5)
	# line 0: name(s)
	# line 1: effect
	# line 2: weight
	# line 3: profile equations
	# line 4: response formats

	'''
	for matchStr in inCmd[1]:
		matchStr= matchStr.replace('juice','')
		inStr = inStr.replace(matchStr, '')
	'''

	# find top match

	maxMatch=0
	topSubstance=[]
	for substance in substances:
		for matchPhrase in substance[0]:
			matchScore = wordSim(matches[0][0], matchPhrase, useInScore=True)
			#print matchPhrase, inStr, matchScore
			if matchScore >= maxMatch:
				maxMatch = matchScore
				topSubstance = substance

	if setting('DEBUG'):
		print "INGESTION SCORE:", topSubstance[0], " - ", maxMatch

	# topSubstance[4]: 

	#replacements = [topSubstance[0][randint(0,len(topSubstance[0])-1)]]
	replacements = topSubstance[0][randint(0,len(topSubstance[0])-1)] #matches[0][0] #
	#rStr = processResponse(getResponse(inCmd), replacements)
	responseForm = topSubstance[4][randint(0,len(topSubstance[4])-1)]
	rStr = processResponse(responseForm, [replacements])
	
	say(rStr, more=False, speak=setting("SPEAK"))



	# now modify mood accordingly
	ingestionTime = time.time()

	#print "appending: ", topSubstance



	GLOB['INGESTED'].append([topSubstance, ingestionTime, "SUBSTANCE"])


	#print "BEFORE UPDATE"
	#print GLOB['MOOD']

	GLOB['MOOD']=updateMood(GLOB['MOOD'], weight=[0]*GLOB['MOODDIM'])

	#print "AFTER SUBSTANCE ADD"
	#print GLOB['MOOD']

	return [topSubstance[0][0], True]
Example #39
0
def killListFile(caller = None):
  os.remove(os.path.join(os.path.abspath(config['realmdir']),"myrealm.cfg"))
  say("WorldList destroyed!")
  global status
  status.push(0,"WorldList destroyed!")