import boto.ec2
import boto.manage.cmdshell
import time
import os.path
import configparser

parser = configparser.ConfigParser()
parser.read("../../halite.ini")
AWS_CONFIG = parser["aws"]
print(AWS_CONFIG)

conn = boto.ec2.connect_to_region("us-east-1", aws_access_key_id=AWS_CONFIG["accessKey"], aws_secret_access_key=AWS_CONFIG["secretAccessKey"])

securityGroup = conn.get_all_security_groups(filters={'group-name': AWS_CONFIG["securityGroupName"]})[0]

reservation = conn.run_instances(AWS_CONFIG["amiID"], key_name=AWS_CONFIG["keyName"], instance_type=AWS_CONFIG["instanceType"], security_groups=[securityGroup])
instance = reservation.instances[0]

status = instance.update()
while status == "pending":
	time.sleep(1)
	status = instance.update()
	print("Waiting for instance to start...")

ssh_client = boto.manage.cmdshell.sshclient_from_instance(instance, os.path.join("../../", AWS_CONFIG["keyFilePath"]), user_name="ubuntu")
configFileContents = open("../../halite.ini").read()
status, stdout, stderr = ssh_client.run("git clone https://github.com/HaliteChallenge/Halite.git; cd Halite; echo '"+configFileContents+"' > halite.ini")
print(stdout)
print(stderr)

@@ -49,16 +49,45 @@
 rt time%0A
+import random%0Aimport pymysql%0A
 import o
@@ -214,26 +214,57 @@
 s%22%5D%0A
-print(AWS_CONFIG)%0A
+DB_CONFIG = parser%5B%22database%22%5D%0A%0A# Create instance
 %0Acon
@@ -403,17 +403,16 @@
 sKey%22%5D)%0A
-%0A
 security
@@ -508,17 +508,16 @@
 %22%5D%7D)%5B0%5D%0A
-%0A
 reservat
@@ -706,16 +706,32 @@
 ces%5B0%5D%0A%0A
+# Wait to start%0A
 status =
@@ -863,16 +863,622 @@
 t...%22)%0A%0A
+# Add worker to db%0Adb = pymysql.connect(host=DB_CONFIG%5B%22hostname%22%5D, user=DB_CONFIG%5B'username'%5D, passwd=DB_CONFIG%5B'password'%5D, db=DB_CONFIG%5B'name'%5D)%0Acursor = db.cursor()%0A%0AipAddress = instance.ip_address%0Aprint(ipAddress)%0A%0AnumRows = 9999%0Awhile numRows != 0:%0A%09apiKey = random.randrange(0, 10000000)%0A%09cursor.execute(%22SELECT * FROM Worker WHERE apiKey=%22+str(apiKey))%0A%09numRows = int(cursor.rowcount)%0Acursor.execute(%22INSERT INTO Worker (apiKey, ipAddress) VALUES (%22+str(apiKey)+%22, '%22+str(ipAddress)+%22')%22)%0A%0A# Wait for ssh to start accepting connections%0Atime.sleep(10)%0A%0A# Connect to ssh%0Afor a in range(100):%0A%09try:%0A%09%09
 ssh_clie
@@ -1608,16 +1608,104 @@
 buntu%22)%0A
+%09%09break%0A%09except Exception as e:%0A%09%09print(%22except%22)%0A%09%09print(str(e))%0A%0A# Run install script%0A
 configFi
@@ -1790,16 +1790,45 @@
 nt.run(%22
+sudo apt-get install -y git; 
 git clon
@@ -1886,16 +1886,34 @@
  Halite;
+ git checkout aws;
  echo '%22
@@ -1947,17 +1947,60 @@
 lite.ini
-%22
+; cd worker; sudo ./install.sh %22+str(apiKey)
 )%0Aprint(

Add workers to db and fix faulty ssh