forked from WebFuzzing/EvoMaster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2020_sw.py
559 lines (402 loc) · 17.2 KB
/
2020_sw.py
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
#!/usr/bin/env python
####
# WARNING: by default, on saga.sigma2.no, might be that python refers to the ancient 2.7 version.
# You might need to add something like:
#
# module load Python/3.7.4-GCCcore-8.3.0
#
# at the end of your .bash_profile in your home folder.
#
# Note: this script was first designed for Abel, but now Saga replaced it.
# Some of the comments/fixes might be no longer required.
###
### Python script used to generate Bash scripts to run on a cluster or locally.
# Given N jobs (ie EvoMaster runs), those will be divided equally among M different
# Bash scripts.
# Once such Bash scripts are generated, on the cluster all of those can be submitted with:
#
# ./runall.sh
#
# they can also be submitted manually with:
#
# for s in `ls *.sh`; do sbatch $s; done
#
#
# Currently, for 100k budget, use 300 minutes as timeout
### Other useful commands on the cluster:
# scancel --user=<your_username> -> to cancel all of your jobs (in case you realized there were problems)
# squeue -u <your_username> -> check your running jobs. to count them, you can pipe it to "| wc -l"
# cost -u <your_username> -> check how much resources (ie CPU time) we can still use
### For interactive session:
# qlogin --account=nn9476k
### More info:
# https://documentation.sigma2.no/quick/saga.html
#
# Max 400 submitted jobs per user at any time.
# Some useful commands as a user on the Abel system are:
#
# sbatch <job-script-file> Submit a job script to the queue system
# squeue List of all jobs
# pending List of all pending jobs
# qsumm Summary information about queue usage
# cost -u User CPU Usage information
# projects Lists the projects you are member of
# module avail Lists available software Modules
# module list Lists your currently used software Modules
# dusage List home directory disk usage
# dusage -p <project> List project disk usage
# scontrol show job <id> Details of a job
### If a job failed due to
# perl: warning: Setting locale failed.
# perl: warning: Please check that your locale settings:
# LANGUAGE = (unset),
# LC_ALL = (unset),
# LC_CTYPE = "UTF-8",
# LANG = "en_US.iso885915"
# are supported and installed on your system.
# you may fix it by executing
# export LANG=en_US.UTF-8
# export LC_ALL=en_US.UTF-8
import io
import os
import pathlib
import random
import shutil
import stat
import statistics
import math
import sys
EXP_ID = "evomaster"
if len(sys.argv) != 9:
print(
"Usage:\n<nameOfScript>.py <cluster> <baseSeed> <dir> <minSeed> <maxSeed> <maxActions> <minutesPerRun> <nJobs>")
exit(1)
### input parameters
# Whether .sh are meant to run on cluster or locally
CLUSTER = sys.argv[1].lower() in ("yes", "true", "t")
# base seeds used for EM runs. TCP port bindings will be based on such seed.
# If running new experiments while some previous are still running, to avoid TCP port
# conflict, can use an higher base seed. Each EM run reserves 10 ports. So, if you run
# 500 jobs with starting seed 10000, you will end up using ports up to 15000
BASE_SEED = int(sys.argv[2])
# When creating a new set of experiments, all needed files will be saved in a folder
BASE_DIR = os.path.abspath(sys.argv[3])
# Experiments are repeated a certain number of times, with different seed for the
# random generator. This specify the starting seed.
MIN_SEED = int(sys.argv[4])
# Max seed, included. For example, if running min=10 and max=39, each experiment is
# going to be repeated 30 times, starting from seed 10 to seed 39 (both included).
MAX_SEED = int(sys.argv[5])
# By default, experiments are run with stopping criterion of number of actions and not time.
MAX_ACTIONS = int(sys.argv[6])
# How many minutes we expect each EM run to last AT MOST.
# Warning: if this value is under-estimated, it will happen the cluster will kill jobs
# that are not finished withing the specified time.
MINUTES_PER_RUN = int(sys.argv[7])
# How many scripts M we want the N jobs to be divided into.
# Note: on cluster we can at most submit 400 scripts.
# Also not that in the same .sh script there can be experiments only for a single SUT.
NJOBS = int(sys.argv[8])
# input parameter validation
if MIN_SEED > MAX_SEED:
print("ERROR: min seed is greater than max seed")
exit(1)
if not os.path.isdir(BASE_DIR):
print("creating folder: " + BASE_DIR)
os.makedirs(BASE_DIR)
else:
print("ERROR: target folder already exists")
exit(1)
### We might want to have different settings based on whether we are running the
### scripts on cluster or locally.
if CLUSTER:
# To ge the SUTs, you need in EMB to run the script "scripts/dist.py" to
# generate a dist.zip file that you can upload on cluster.
# Note: the values after the SUT names is multiplicative factor for how long
# experiments should be run. For example, all SUTs have similar runtime, but
# proxyprint is roughly twice as slow.
# Depending on what experiments you are running, might want to de-select some
# of the SUTs (eg, by comment them out)
SUTS = [
("features-service", 1),
("scout-api", 2),
("proxyprint", 2),
("rest-ncs", 2),
("rest-scs", 1),
("rest-news", 1),
("catwatch", 1)
]
HOME = os.environ['HOME']
EVOMASTER_DIR = HOME
CASESTUDY_DIR = HOME + "/dist"
LOGS_DIR = os.environ['USERWORK']
## Local configurations
else:
# These SUTs require Docker
SUTS = [
("ind0", 1),
("ocvn-rest", 1)
]
# You will need to define environment variables on your OS
EVOMASTER_DIR = os.environ.get("EVOMASTER_DIR", "")
EMB_DIR = os.environ.get('EMB_DIR',"")
if EVOMASTER_DIR == "":
raise Exception("You must specify a EVOMASTER_DIR env variable specifying where evomaster.jar can be found")
if EMB_DIR == "":
raise Exception("You must specify a EMB_DIR env variable specifying the '/dist' folder from where EMB repository was cloned")
CASESTUDY_DIR = EMB_DIR
if not os.path.exists(CASESTUDY_DIR):
raise Exception(CASESTUDY_DIR + " does not exist. Did you run script/dist.py?")
ind0_package = os.environ.get("SUT_PACKAGE_IND0", "")
if ind0_package == "":
raise Exception("You cannot run experiments on IND0 without specify target package to cover with SUT_PACKAGE_IND0 env variable")
LOGS_DIR = BASE_DIR
# How to run EvoMaster
EVOMASTER = "java -Xms2G -Xmx4G -jar evomaster.jar"
AGENT = "evomaster-agent.jar"
EM_POSTFIX = "-evomaster-runner.jar"
SUT_POSTFIX = "-sut.jar"
if NJOBS < len(SUTS):
print("ERROR: you need at least one job per SUT, and those are " + str(len(SUTS)))
exit(1)
# Where to put stuff (default in subdirs of BASEDIR)
REPORT_DIR = BASE_DIR + "/reports"
os.makedirs(REPORT_DIR)
SCRIPT_DIR = BASE_DIR + "/scripts"
os.makedirs(SCRIPT_DIR)
TEST_DIR = BASE_DIR + "/tests"
os.makedirs(TEST_DIR)
ALL_LOGS = LOGS_DIR + "/logs"
#We might end up generating gigas of log files. So, at each new experiments, we delete previous logs
shutil.rmtree(ALL_LOGS, ignore_errors=True)
LOG_DIR = ALL_LOGS + "/" + EXP_ID
os.makedirs(LOG_DIR)
CONTROLLER_PID = "CONTROLLER_PID"
### By default, we allocate 3 CPUs per run.
### Recall that we are running 3 processes, and they are multithreaded.
CPUS = 3
TIMEOUT_SUT_START_MINUTES = 20
if not CLUSTER:
REPORT_DIR = str(pathlib.PurePath(REPORT_DIR).as_posix())
SCRIPT_DIR = str(pathlib.PurePath(SCRIPT_DIR).as_posix())
TEST_DIR = str(pathlib.PurePath(TEST_DIR).as_posix())
LOG_DIR = str(pathlib.PurePath(LOG_DIR).as_posix())
#Due to Windows limitations (ie crappy FS), we need to copy JARs over
for sut in SUTS:
sut_name = sut[0]
shutil.copy(os.path.join(CASESTUDY_DIR, sut_name + EM_POSTFIX), BASE_DIR)
shutil.copy(os.path.join(CASESTUDY_DIR, sut_name + SUT_POSTFIX), BASE_DIR)
shutil.copy(os.path.join(CASESTUDY_DIR, AGENT), BASE_DIR)
shutil.copy(os.path.join(EVOMASTER_DIR, "evomaster.jar"), BASE_DIR)
def createRunallScript():
script_path = BASE_DIR + "/runall.sh"
script = open(script_path, "w")
script.write("#!/bin/bash \n\n")
script.write("cd \"$(dirname \"$0\")\"\n\n")
script.write("for s in `ls scripts/*.sh`; do\n")
script.write(" echo Going to start $s\n")
if CLUSTER:
script.write(" sbatch $s\n")
else:
script.write(" $s & \n")
script.write("done \n")
st = os.stat(script_path)
os.chmod(script_path, st.st_mode | stat.S_IEXEC)
def writeScript(code, port, sut_name):
script_path = SCRIPT_DIR + "/evomaster_" + str(port) + "_" + sut_name + ".sh"
script = open(script_path, "w")
script.write(code)
st = os.stat(script_path)
os.chmod(script_path, st.st_mode | stat.S_IEXEC)
return script
def getScriptHead(timeoutMinutes):
s = "#!/bin/bash \n"
if CLUSTER:
s += "#SBATCH --job-name=" + EXP_ID + " \n"
s += "#SBATCH --account=nn9476k \n"
s += "#SBATCH --mem-per-cpu=4G \n"
s += "#SBATCH --nodes=1 --ntasks-per-node=" + str(CPUS) + " \n"
s += "#SBATCH --time=" + str(timeoutMinutes) + ":00 \n\n"
return s
def createJobHead(port, sut_name, timeoutMinutes):
script = io.StringIO()
script.write(getScriptHead(timeoutMinutes))
sut_log = LOG_DIR + "/log_sut_" + sut_name + "_" + str(port) + ".txt"
# Start SUT as background process on the given port
controllerPort = str(port)
sutPort = str(port + 1)
em_runner = sut_name + EM_POSTFIX
em_sut = sut_name + SUT_POSTFIX
if CLUSTER:
sut_em_path = os.path.join(CASESTUDY_DIR, em_runner)
sut_jar_path = os.path.join(CASESTUDY_DIR, em_sut)
agent_path = os.path.join(CASESTUDY_DIR, AGENT)
script.write("\nmodule load Java/1.8.0_212\n\n")
script.write("cd $SCRATCH \n")
script.write("cp " + EVOMASTER_DIR + "/evomaster.jar . \n")
script.write("cp " + sut_em_path + " . \n")
script.write("cp " + sut_jar_path + " . \n")
script.write("cp " + agent_path + " . \n")
script.write("\n")
script.write("\n")
timeoutStart = TIMEOUT_SUT_START_MINUTES * 60
params = " " + controllerPort + " " + sutPort + " " + em_sut + " " + str(timeoutStart)
# JVM properties
jvm = " -Xms1G -Xmx4G -Dem.muteSUT=true -Devomaster.instrumentation.jar.path="+AGENT
command = "java " + jvm + " -jar " + em_runner + " " + params + " > " + sut_log + " 2>&1 &"
if not CLUSTER:
script.write("\n\necho \"Starting EM Runner with: " + command + "\"\n")
script.write("echo\n\n")
script.write(command + "\n\n")
script.write(CONTROLLER_PID + "=$! \n\n") # store pid of process, so can kill it
script.write("sleep 20 \n\n") # wait a bit to be sure the SUT handler can respond
return script.getvalue()
def closeJob(port, sut_name):
return "kill $" + CONTROLLER_PID + "\n"
####################################
class State:
def __init__(self, budget):
self.budget = budget
generated = 0
waits = []
jobsLeft = NJOBS
sutsLeft = len(SUTS)
counter = 0
opened = False
perJob = 0
port = BASE_SEED
def updatePerJob(self):
if self.jobsLeft == 0:
self.perJob = 0
else:
self.perJob = self.budget / self.jobsLeft
def updatePort(self):
self.port += 10
def updateBudget(self, weight):
self.counter += weight
self.budget -= weight
def getTimeoutMinutes(self):
timeoutMinutes = TIMEOUT_SUT_START_MINUTES + int(math.ceil(1.1 * self.counter * MINUTES_PER_RUN))
self.waits.append(timeoutMinutes)
return timeoutMinutes
def resetTmpForNewRun(self):
self.counter = 0
self.opened = False
self.updatePerJob()
self.updatePort()
def hasSpareJobs(self):
return self.jobsLeft > self.sutsLeft
def writeWithHeadAndFooter(code, port, sut_name, timeout):
head = createJobHead(port, sut_name, timeout)
footer = closeJob(port, sut_name)
code = head + code + footer
writeScript(code, port, sut_name)
def createOneJob(state, sut_name, seed, weight, config):
code = addJobBody(state.port, sut_name, seed, config, weight)
state.updateBudget(weight)
state.jobsLeft -= 1
state.opened = True
state.generated += 1
return code
def addJobBody(port, sut_name, seed, config, weight):
script = io.StringIO()
em_log = LOG_DIR + "/log_em_" + sut_name + "_" + str(port) + ".txt"
params = customParameters(seed, config)
### standard
params += " --stoppingCriterion=FITNESS_EVALUATIONS"
params += " --maxActionEvaluations=" + str(MAX_ACTIONS)
params += " --statisticsColumnId=" + sut_name
params += " --seed=" + str(seed)
params += " --sutControllerPort=" + str(port)
params += " --outputFolder=" + TEST_DIR + "/" + sut_name
params += " --statisticsFile=" + \
REPORT_DIR + "/statistics_" + sut_name + "_" + str(seed) + ".csv"
params += " --snapshotInterval=5"
params += " --snapshotStatisticsFile=" + \
REPORT_DIR + "/snapshot_" + sut_name + "_" + str(seed) + ".csv"
params += " --appendToStatisticsFile=true"
params += " --writeStatistics=true"
params += " --showProgress=false"
command = EVOMASTER + params + " >> " + em_log + " 2>&1"
if not CLUSTER:
script.write("\n\necho \"Starting SUT with: " + command + "\"\n")
script.write("echo\n\n")
if CLUSTER:
timeout = int(math.ceil(1.1 * weight * MINUTES_PER_RUN * 60))
errorMsg = "ERROR: timeout for " + sut_name
command = "timeout " +str(timeout) + " " + command \
+ " || ([ $? -eq 124 ] && echo " + errorMsg + " >> " + em_log + " 2>&1" + ")"
script.write(command + " \n\n")
return script.getvalue()
def createJobs():
CONFIGS = getConfigs()
NRUNS_PER_SUT = (1 + MAX_SEED - MIN_SEED) * len(CONFIGS)
SUT_WEIGHTS = sum(map(lambda x: x[1], SUTS))
state = State(NRUNS_PER_SUT * SUT_WEIGHTS)
SUTS.sort(key=lambda x: -x[1])
for sut in SUTS:
sut_name = sut[0]
weight = sut[1]
state.sutsLeft -= 1
state.resetTmpForNewRun()
code = ""
completedForSut = 0
for seed in range(MIN_SEED, MAX_SEED + 1):
random.shuffle(CONFIGS)
for config in CONFIGS:
if state.counter == 0:
code = createOneJob(state, sut_name, seed, weight, config)
elif (state.counter + weight) < state.perJob \
or not state.hasSpareJobs() or \
(NRUNS_PER_SUT - completedForSut < 0.3 * state.perJob / weight):
code += addJobBody(state.port, sut_name, seed, config, weight)
state.updateBudget(weight)
else:
writeWithHeadAndFooter(code, state.port, sut_name, state.getTimeoutMinutes())
state.resetTmpForNewRun()
code = createOneJob(state, sut_name, seed, weight, config)
completedForSut += 1
if state.opened:
writeWithHeadAndFooter(code, state.port, sut_name, state.getTimeoutMinutes())
print("Generated scripts: " + str(state.generated))
print("Max wait for a job: " + str(max(state.waits)) + " minutes")
print("Median wait for a job: " + str(statistics.median(state.waits)) + " minutes")
print("Budget left: " + str(state.budget))
print("Total time: " + str(sum(state.waits) / 60) + " hours")
print("Total budget: " + str(CPUS * sum(state.waits) / 60) + " hours")
############################################################################
### Custom
### Following will need to be changed based on what kind of experiments
### we want to run.
############################################################################
class Config:
def __init__(self, blackBox, algorithm):
self.blackBox = blackBox
self.bbExperiments = blackBox
self.algorithm = algorithm
def customParameters(seed, config):
params = ""
label = str(config.blackBox)
### Custom for these experiments
params += " --testSuiteFileName=EM_" + label + "_" + str(seed) + "_Test"
params += " --blackBox=" + str(config.blackBox)
params += " --bbExperiments=" + str(config.blackBox)
params += " --algorithm=" + str(config.algorithm)
params += " --heuristicsForSQL=" + str(not config.blackBox)
params += " --extractSqlExecutionInfo=" + str(not config.blackBox)
params += " --generateSqlDataWithSearch=" + str(not config.blackBox)
return params
def getConfigs():
# array of configuration objects. We will run experiments for each of
# these configurations
CONFIGS = []
CONFIGS.append(Config(True, "RANDOM"))
CONFIGS.append(Config(False, "MIO"))
return CONFIGS
############################################################################
#### END of custom configurations
############################################################################
# Create the actual job scripts
createJobs()
# Create a single ./runall.sh script to submit all the job scripts
createRunallScript()