Source

is-solver / awslauncher / createISS_compstatic_tasks.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
#!/usr/bin/env python

# this script pulls messages from SQS
from boto.sqs.connection import SQSConnection
from boto.sqs.message import Message
from datetime import datetime

import boto
import boto.s3
from boto.s3.key import Key
from boto.s3.connection import S3Connection

import time
import os
import sys
sys.path.append(os.getcwd())
import random
import optparse
import subprocess
import socket
import uuid
from collections import OrderedDict
import numpy as np
import simple__serialize
from barrLogger import *
#import Getch

try:
  import awscreds
except:
  print("awscreds.py file needed with access and secret globals for aws access")
  sys.exit(1)


def getHostIP():
  HOST_IP = "127.0.0.1"
  try:
    HOST_IP = subprocess.check_output(["curl", "http://169.254.169.254/latest/meta-data/public-ipv4", "-s"])
  except subprocess.CalledProcessError, e:
    HOST_IP = socket.gethostbyname(socket.gethostname())
  return (HOST_IP)
########################################

import sys    
import termios
import fcntl

def getch():
  fd = sys.stdin.fileno()

  oldterm = termios.tcgetattr(fd)
  newattr = termios.tcgetattr(fd)
  newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
  termios.tcsetattr(fd, termios.TCSANOW, newattr)

  oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
  fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

  try:        
    while 1:            
      try:
        c = sys.stdin.read(1)
        break
      except IOError: pass
  finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
  return c



#####################################################################


def takeInputs(xd):
  keys = xd.keys()
  print "Input Editor";
  print "Enter to accept default, e to edit";
  for k in keys:
    print k + ": [" + str(xd[k]) + "]"
    var = raw_input("    [DEFAULT] or  RANGE as 'start,stop,N'")
    if var == "":
      # accept default
      continue
    else:
      rangeinput = str.split(var, ',')
      start = float(rangeinput[0])
      stop = float(rangeinput[1])
      length = int(rangeinput[2])
      inrange = np.linspace(start,stop, length)
      print "NEW: " + str(inrange)
      xd[k] = inrange
  return(xd)




#############################################################################
#
# 
#
def initial_run_populate(runs_dpi_domain,
                         s3bucket,
                         awsKey,
                         awsSecret,
                         my_guid,
                         bigtable, 
                         jobname):
    """
    :param runs_dpi_domain:
    :param filelist:
    :param s3bucket:
    :param awsKey:
    :param awsSecret:
    :param my_guid: the guid for which we are populating the runs domain
    :param bigtable: a table of arguments to put in 
    :param jobname: the name of the job

    Once dpclient is populated, populate the runs_dpi_table. Setting queuename = PSEUDO_NULL_STRING indicates that it has not yet been placed into a queue
    """

    dtnow = str(datetime.now().isoformat())

    logging_conn = boto.connect_sdb(awscreds.aws_access, awscreds.aws_secret)
    domain = logging_conn.create_domain(runs_dpi_domain)
    domain = logging_conn.get_domain(runs_dpi_domain)
    PSEUDO_NULL_STRING = "PSEUDONULL"

    log_set = {}
    counter = 0
    counterTotal = 0

    tostring = np.vectorize(lambda x: str(x))

    print "POPULATING GUID: " + my_guid
    for i in range(0, bigtable.shape[0]):            
        myrow = bigtable[i,:]
        xrow = list(tostring(myrow))
        csv_row = ",".join(xrow)

        log_entry = {}
        log_entry['datetime'] = dtnow
        log_entry['uuid_g'] = my_guid
        log_entry['uuid_i'] = str(uuid.uuid4())
        log_entry['s3_bucket'] = s3bucket
        log_entry['paramstr'] = csv_row
        log_entry['queuename'] = PSEUDO_NULL_STRING
  
        log_set[str(uuid.uuid4())] = log_entry
        counter += 1
        counterTotal += 1

        if counter > 16:
            print "Length of batch put: " + str(len(log_set)) + ", " + str(counterTotal) + "/" + str(bigtable.shape[0])
            print( "Queueing " + str(len(log_set)) + "/" + str(bigtable.shape[0]) + " jobs to " + runs_dpi_domain)
            domain.batch_put_attributes(log_set)
            log_set.clear()
            counter = 0


    ## after the for loop, clean out the last of them
    if len(log_set) > 0:
      print( "Queueing " + str(len(log_set)) + "/" + str(bigtable.shape[0]) + " jobs to " + runs_dpi_domain)
      domain.batch_put_attributes(log_set)
      log_set.clear()


##########################################################
## add the junk to sqs
def add_to_sqs_from_runs_dpi_domain(uuid_g,
                                    runs_dpi_domain, 
                                    queueName,
                                    Nqueueentries,
                                    barr_logger_obj,
                                    awsKey,
                                    awsSecret):
    """
    :param uuid_g:
    :param runs_dpi_domain:
    :param queueName:
    :param Nqeueentries:
    :param barr_logger_obj:
    :param awsKey:
    :param awsSecret:


    Read the runs_dpi_domain and put into queueName. N tasks.

    """
    N = Nqueueentries

    # query runs dpi domain
    uuid_g_query = "SELECT * FROM `" + runs_dpi_domain + "`"
    uuid_g_query += " where uuid_g = '" + str(uuid_g) + "'"
    uuid_g_query += " and queuename = 'PSEUDONULL'"

    logging_conn = boto.connect_sdb(awsKey, awsSecret)
    domain = logging_conn.create_domain(runs_dpi_domain)
    domain = logging_conn.get_domain(runs_dpi_domain)
    PSEUDO_NULL_STRING = "PSEUDONULL"


    print "QUERY: " + uuid_g_query

    # gather up the results of the query
    rsr = domain.select(uuid_g_query)
    itemdict = {}
    for item in rsr:
        itemdict[item.name] = item

    # create an SQS queue connection
    conn = SQSConnection(awsKey, awsSecret)
    q = conn.create_queue(queueName)

    #take at most N random items from the list
    keylist = itemdict.keys()
    random.shuffle(keylist)

    if N < 0:
        N = len(keylist)
    lastone = len(keylist) if  len(keylist) < N else N

    print "Adding " + str(lastone)

    uuid_i_list = []

    # add them to the queue
    for i in range(0,lastone):
        key = keylist[i]
        item = itemdict[key]
        paramstr = item['paramstr']
        s3bucket = item['s3_bucket']
        uuid_i = item['uuid_i']

        queuemessage = paramstr + "," + s3bucket + "," + uuid_i + "," + uuid_g

        m = Message()
        m.set_body(queuemessage)
        status = q.write(m)
        
        
        uuid_i_obj = uuidobj(uuid_i, uuid_g)
        if not status:
            print("FAILED Message: " + queuemessage)
        else:
            print("SUCCESS Message: " + queuemessage)

        print uuid_i_obj.uuid + "queue_add_hw:add_to_sqs_from_runs_dpi_domain -- SQS queue created"
        barr_logger_obj.log(uuid_i_obj, "queue_add_hw:add_to_sqs_from_runs_dpi_domain", "SQS queue created")
        barr_logger_obj.flush()

        # updating simpledb
        update_hash = {}
        update_hash['queuename'] = queueName
        domain.put_attributes(keylist[i], update_hash, replace=True)
        print uuid_i_obj.uuid + "queue_add_hw:add_to_sqs_from_runs_dpi_domain -- simpledb updated"
        uuid_i_list.append(uuid_i)

    return(uuid_g, uuid_i_list)


class uuidobj:
    def __init__(self,
                 uuid,
                 guid):
        self.uuid = str(uuid)
        self.guid = str(guid)


def launch_cs(paramDict,
              runs_domain,
              queueName,
              jobname):

  # main logic:
  uuid_g = str(uuid.uuid4())
  print "GROUP uuid: " + uuid_g + " GENERATED"
  ptable = simple__serialize.serializeState(paramDict)

  ####### CHECK IF THIS IS OKAY
  print("========================================")
  print("ABOUT TO DO THE FOLLOWING:")
  print("- create " + str(ptable.shape[0]) + " jobs")
  print("- create entries in " + runs_domain)
  print("- create SQS tasks in " + queueName)
  ans = raw_input("Press [ENTER] to continue or q to quit")

  if not ans == "":
    print("ABANDON SHIP")
    #sys.exit(1)
    return

  print("============POPULATING RUNS");

  # call initial_run_populate on arglist
  initial_run_populate(runs_domain, bucketName, awscreds.aws_access, awscreds.aws_secret, uuid_g, ptable, jobname)

  bl = barrLogger(simple_db_log_domain)
  uuid_g, uuid_i_list = add_to_sqs_from_runs_dpi_domain(uuid_g, runs_domain, queueName, -1, bl, awscreds.aws_access, awscreds.aws_secret)

  bl.flush()

  print("========================================")
  print("SUMMARY: ")
  print("- created " + str(ptable.shape[0]) + " jobs")
  print("- created entries in " + runs_domain)
  print("- created SQS tasks in " + queueName)
  print("-----")
  print("UUID_G: " + uuid_g)
  for ui in uuid_i_list:
    print("\t" + ui)

  print("========================================")
  ugmap_path = '/home/stevejb/mnt/cs/ugmap.csv'
  print("Appending to " + ugmap_path)
  f = open(ugmap_path, 'a')

  for ui in uuid_i_list:
    uuistr = '"' + uuid_g + '","' + ui + '"\n'
    f.write(uuistr)
    print(uuistr.strip())
  f.close()

  print("UUID_G: " + uuid_g)

  ugDict = OrderedDict()
  ugDict[uuid_g] = uuid_i_list
  return(ugDict)


def makelinspacedict(paramDict):
  for k in paramDict.keys():
    if(len(paramDict[k]) == 3):
      rangeinput = paramDict[k]
      start = float(rangeinput[0])
      stop = float(rangeinput[1])
      length = int(rangeinput[2])
      inrange = np.linspace(start,stop, length)
      paramDict[k] = inrange
    if(k == "epsilon_P"):
      print("Taking log")
      paramDict[k] = np.log(paramDict[k])
      print str(paramDict[k])
  return(paramDict)
  


####################################################################
# main


# HOST_IP = getHostIP()
# print("HOST_IP:" + str(HOST_IP))

# parse incoming arguments
parser = optparse.OptionParser()
parser.add_option('-q', help='specify name of an aws queue', dest='queueName')
parser.add_option('-s', help='s3 bucket to place the output', dest='s3bucket')
parser.add_option('-l', help='SimpleDB log domain', dest='simple_db_log')
parser.add_option('-r', help='Runs domain - a table to store mappings of the parameteriztions', dest='runs_domain')
parser.add_option('-j', help='job name, mandatory', dest='jobname')
parser.add_option('-n', "--notest", dest='no_test', action="store_const", const=0,
                  help='Disables adding to test buckets (default)')

(opts, args) = parser.parse_args()

basename = "barr_iss_"
bucketName = basename + "storage"
queueName = basename + "q"
simple_db_log_domain = basename + "log"
runs_domain = basename + "runs"
jobname = ""
isTest = True

if opts.s3bucket:
    bucketName = opts.s3bucket
if opts.queueName:
    queueName = opts.queueName
if opts.simple_db_log:
  simple_db_log_domain = opts.simple_db_log
if opts.runs_domain:
    runs_domain = opts.runs_domain
if opts.jobname:
  jobname = opts.jobname
else:
  print "Jobname required"
  exit(1)

if opts.no_test == 0:
  isTest = False
else:
  basename             = basename + "___test"
  bucketName           = bucketName + "___test"
  queueName            = queueName + "___test"
  simple_db_log_domain = simple_db_log_domain  + "___test"
  runs_domain          = runs_domain + "___test"
  jobname              = jobname + "___test"

print("========================================")
print("PARAMS: " )
print("basename: " + basename)
print("bucketName: "  + bucketName)
print("queueName: "            + queueName)
print("simple_db_log_domain:" + simple_db_log_domain)
print("runs_domain:"          + runs_domain)
print("jobname:"          + jobname)

#####################################

###### present the paramters for editing
paramDict = OrderedDict()
paramDict['theta']     = np.array([0.7880])
paramDict['rho']       = np.array([0.3])
paramDict['sigma_v']   = np.array([0.2843])
paramDict['a']         = np.array([0.03])
paramDict['gamma']     = np.array([0.003370])
paramDict['s']         = np.array([0.0077])
paramDict['lambda_1']  = np.array([0.161535])
paramDict['lambda_2']  = np.array([0.004142])
paramDict['sigma_p']   = np.array([0.5])
paramDict['r']         = np.array([0.015])
paramDict['delta']     = np.array([0.15])
paramDict['tau_c']     = np.array([0.35])
paramDict['epsilon_P'] = np.array([0.015])

paramDict = takeInputs(paramDict)


###### csRanges
csRanges = OrderedDict()
# csRanges['theta']     = np.array([0.5, 0.95, 50])
# csRanges['rho']       = np.array([0.15, 0.95, 50])
# csRanges['sigma_v']   = np.array([0.01, 0.6, 50])
# csRanges['a']         = np.array([0.001, 0.1, 50])
# csRanges['gamma']     = np.array([0.0001, 0.1, 50])
# csRanges['s']         = np.array([0.0001, 0.1, 50])
# csRanges['lambda_1']  = np.array([0.01, 0.5, 50])
# csRanges['lambda_2']  = np.array([0.001, 0.1, 50])
# csRanges['sigma_p']   = np.array([0.50])
# csRanges['r']         = np.array([0.01, 0.2, 20])
# csRanges['delta']     = np.array([0.01, 0.3, 30])
# csRanges['tau_c']     = np.array([0.350])
csRanges['epsilon_P'] = np.array([0.001, 0.05, 50])


## USAGE:
## ugdict = launch_cs(paramDict, runs_domain, queueName, jobname)

cskeys = csRanges.keys()
csAllDict = OrderedDict()

usedkeys = []

for i in range(len(cskeys)):
  keytmp  = cskeys[i]
  tmpparam = paramDict.copy()
  tmpparam[keytmp] = csRanges[keytmp]

  if len(tmpparam[keytmp]) <= 1:    
    print "skipping " + keytmp
  else:
    print "doing " + keytmp
    usedkeys.append(keytmp)
    tmpparam = makelinspacedict(tmpparam)
    tmp_uuid_dict = launch_cs(tmpparam, runs_domain, queueName, jobname)
    csAllDict.update(tmp_uuid_dict)

print("========================================")
print("=========== FINAL SUMMARY ==============") 

print "UUIDG\t param"

csAllkeys = csAllDict.keys()
print "| GUID | param | min | max | "
for ki in range(len(usedkeys)):
  print csAllkeys[ki] + " |  " + usedkeys[ki] + "  |  " + str(csRanges[usedkeys[ki]][0]) + "  |  " + str(csRanges[usedkeys[ki]][1]) + " |"

print "Param defaults"
for pp in paramDict:
  print pp + str(paramDict[pp])