Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Reorganize output files
Files output by simulation are reorganized. Session GUID won't be appended to file names.
Restructure file download URL syntax.
Fixed some minor typos in codes.
Remove mkdir in server initialization.
Remove cleanup script.
  • Loading branch information
yat17006 committed Mar 26, 2021
1 parent 13c506a commit 8ac51c6
Show file tree
Hide file tree
Showing 9 changed files with 50 additions and 62 deletions.
16 changes: 12 additions & 4 deletions Python/filegenerator.py
Expand Up @@ -13,14 +13,22 @@ class filegenerator:
MaxQueueSize, DDDMappingDelay, PropDelay,
NumbDDDPortsOpen, bandwidths, timeUntilNextDDDChange,
overlapTime, numbSynAckResends, attackerType,
isAmplification,sessionId):
isAmplification, storageFolder, sessionId):
# boolean statements for deciding which files to make
self.makeLog = make_log
self.makeSummary = make_summary
self.makeAnimation = make_animation
# Make folders
try:
os.mkdir(storageFolder)
except FileExistsError:
pass # This error is to be expected.
# If FileExistsError happens here, this means a GUID collision. I don't think it is possible.
os.mkdir(os.path.join(storageFolder, str(sessionId)))
self.storageFolder = os.path.join(storageFolder, str(sessionId))
# File Name to be used
self.logFileName = os.path.join("logs", "log-{0}.csv".format(str(sessionId)))
self.summaryFileName = os.path.join("summaries", "summary-{0}.csv".format(str(sessionId)))
self.logFileName = os.path.join(self.storageFolder, "log.csv")
self.summaryFileName = os.path.join(self.storageFolder, "summary.csv")
# names of the output files
self.logName = log_name
self.summaryName = summary_name
Expand Down Expand Up @@ -598,5 +606,5 @@ class filegenerator:
plt.title("Packets " + name + " vs. Time")
plt.legend()

plt.savefig(os.path.join("plots", name + "-{0}.svg".format(str(self.sessionId))))
plt.savefig(os.path.join(self.storageFolder, name + ".svg"))
plt.close()
5 changes: 3 additions & 2 deletions Python/main.py
Expand Up @@ -23,7 +23,8 @@ def runSimulation(dddState, skipsim, sumOut,
routertoClient, routertoReflector,
routertoNormal, normaltoRouter,
reflectortoRouter, attackertoReflector,
queueLimit, attackerType, amplification):
queueLimit, attackerType, amplification,
storageFolder):
# For a simulation session, we create a unique session id for it using GUID.
sessionGuid = uuid.uuid4() # Generate a GUID/UUID for this session

Expand All @@ -40,7 +41,7 @@ def runSimulation(dddState, skipsim, sumOut,
NumbDDDPortsOpen, bandwidths,
timeUntilNextDDDChange, overlapTime,
numbSynAckResends, attackerType,
amplification, sessionGuid)
amplification, storageFolder, sessionGuid)

debug_mode = False

Expand Down
5 changes: 0 additions & 5 deletions cleanup.bat

This file was deleted.

27 changes: 16 additions & 11 deletions pserver.py
Expand Up @@ -16,8 +16,8 @@ def runSimulation(input1):
# Parse simulation parameters.
Param = input1.split("&") # Parameters are separated by '&' delimiter.
print(Param)
# Check parameter count.
if len(Param)==24: # VERY-IMPORTANT: Modify here if there are changes to total number of requests!
# Check parameter count. If simulation never happens then check here!
if len(Param)==25: # VERY-IMPORTANT: Modify here if there are changes to total number of requests!
ddd_state = (Param[0] == "true")
skip_sim = (Param[1] == "true")
sumOut = (Param[2] == "true")
Expand All @@ -43,6 +43,7 @@ def runSimulation(input1):
queueLimit = int(Param[21])
attackerType = float(Param[22])
amplification = float(Param[23])
storageFolder = Param[24]

response = main.runSimulation(ddd_state, skip_sim, sumOut,
logOut, packet_size, rtsa,
Expand All @@ -53,7 +54,7 @@ def runSimulation(input1):
routertoClient, routertoReflector, routertoNormal,
normaltoRouter, reflectortoRouter,
attackertoReflector, queueLimit, attackerType,
amplification)
amplification, storageFolder)

print('Backend Simulation Total Elapsed Time:', time.time() - start_time, 'seconds')

Expand All @@ -63,31 +64,35 @@ def runSimulation(input1):
abort(400)


@app.route('/download/<fileName>') # This is the endpoint that the javascript code will call to run simulation on server
def download(fileName):
@app.route('/download/<storageFolder>/<sessionId>/<fileName>') # This is the endpoint that the javascript code will call to run simulation on server
def download(storageFolder, sessionId, fileName):
try:
if fileName.startswith("log"):
return send_file(os.path.join("logs", fileName), as_attachment=True)
return send_file(os.path.join(storageFolder, sessionId, fileName), as_attachment=True)
elif fileName.startswith("summary"):
return send_file(os.path.join("summaries", fileName), as_attachment=True)
return send_file(os.path.join(storageFolder, sessionId, fileName), as_attachment=True)
elif fileName.endswith(".svg"):
return send_file(os.path.join(storageFolder, sessionId, fileName), as_attachment=True)
else:
abort(400)
except FileNotFoundError:
abort(404)


@app.route('/download2/<statement>')
def download2(statement):
@app.route('/download2/<storageFolder>/<sessionId>/<statement>')
def download2(storageFolder, sessionId, statement):
# We may use split function to process the request.
tmp = statement.split("&")
fileName = tmp[0]
newName = tmp[1]
if len(tmp)==2:
try:
if fileName.startswith("log"):
return send_file(os.path.join("logs", fileName), as_attachment=True, attachment_filename=newName)
return send_file(os.path.join(storageFolder, sessionId, fileName), as_attachment=True, attachment_filename=newName)
elif fileName.startswith("summary"):
return send_file(os.path.join("summaries", fileName), as_attachment=True, attachment_filename=newName)
return send_file(os.path.join(storageFolder, sessionId, fileName), as_attachment=True, attachment_filename=newName)
elif fileName.endswith(".svg"):
return send_file(os.path.join(storageFolder, sessionId, fileName), as_attachment=True, attachment_filename=newName)
else:
abort(400)
except FileNotFoundError:
Expand Down
29 changes: 4 additions & 25 deletions readme.md
Expand Up @@ -17,22 +17,15 @@ pip install flask
pip install matplotlib
```

3. If it is your first time to run the server, you should create some folders:
```bat
mkdir logs
mkdir summaries
mkdir plots
```

4. Execute the following commands to run flask:
3. Execute the following commands to run flask:
```bat
set FLASK_APP=pserver
set FLASK_ENV=development
python -m flask run
```
Alternatively, you may double-click `run_server.bat` file in lieu of manually typing these commands.

5. In certain circumstances, your system might be configuring the `*.js` files with incorrect treatings. Locate registry key `HKEY_CLASSES_ROOT\.js` and edit the key value `Content Type` to be `text/javascript`. <br>
4. In certain circumstances, your system might be configuring the `*.js` files with incorrect treatings. Locate registry key `HKEY_CLASSES_ROOT\.js` and edit the key value `Content Type` to be `text/javascript`. <br>
Please note that you are all set if key value `Content Type` does not exist in `HKEY_CLASSES_ROOT\.js` key at all: just leave the registry as is. Usually, things are problematic if the value of `Content Type` equals to `text/plain`.

### Option 2: Get Started on Windows with WSL
Expand All @@ -55,25 +48,11 @@ Link: https://www.digitalocean.com/community/tutorials/how-to-make-a-web-applica
```bash
export FLASK_APP=pserver
export FLASK_ENV=development
```

### To run the server:
1) Navigate to the top of this repo
2) If it is your first time to run the server, then run
```bat
mkdir summaries
mkdir logs
mkdir plots
```

3) Run the following
```bat
flask run
```

## Summary and Log Files
For each session, the backend would generate a summary file and a log file. They will be separately placed in two directories: `logs` and `summaries`. <br>
There is also a `cleanup.bat`. If you would like to delete all summaries and logs for previous sessions, run it. <br>
## Output Files
For each simulation session, the backend would generate a summary file, a log file and several statistical graphs. Their locations are specified by your input on frontend. <br>

## License
This project is under NCSA License. For more information, view the [license](license.txt).
3 changes: 0 additions & 3 deletions run_server.bat
@@ -1,8 +1,5 @@
@echo off
set FLASK_APP=pserver
set FLASK_ENV=development
mkdir logs
mkdir summaries
mkdir plots
python -m flask run
pause.
3 changes: 0 additions & 3 deletions run_server.sh
Expand Up @@ -2,7 +2,4 @@

export FLASK_APP=pserver
export FLASK_ENV=development
mkdir logs
mkdir summaries
mkdir plots
flask run
16 changes: 9 additions & 7 deletions static/js/requests.js
Expand Up @@ -32,9 +32,10 @@ var attackertoReflector;
var queueLimit;
var attackerType;
var amplification;
var storageFolder;

// When simulation started, we will retrieve a session ID.
var sessionId
var sessionId;

function startSimulation(){
DDDstate = document.getElementById("DDDstate").checked;
Expand Down Expand Up @@ -73,6 +74,7 @@ function startSimulation(){
queueLimit=document.getElementById("queueLimit").value;
attackerType = document.getElementById("AtkType").value;
amplification = document.getElementById("Amp").value;
storageFolder = document.getElementById("storageFolder").value;
}

// sendGet is the function that is called when user presses button on index.html
Expand All @@ -84,7 +86,7 @@ function sendGet(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
let jsonObj = JSON.parse(xmlHttp.responseText);
sessionId = jsonObj[jsonObj.length - 1];
console.log('Session GUID = ' + sessionId)
console.log('Session GUID = ' + sessionId);
console.log('length of animateInstructions list is ' + jsonObj.length);
setAnimateInstructions(jsonObj);
}
Expand All @@ -98,7 +100,7 @@ function sendGet(){
dddmappingdelay+ "&" + propagationdelay + "&" + numofDDDport + "&" + timetonextDDDport +"&" + overlaptimeoldDDD
+ "&" + durationSim + "&" + numbSynAckResends + "&" + clienttoRouter + "&" + routertoClient + "&" +
routertoReflector + "&" + routertoNormal + "&" + normaltoRouter + "&" + reflectortoRouter + "&" + attackertoReflector + "&" + queueLimit +"&" + attackerType + "&"
+ amplification;
+ amplification + "&" + storageFolder;
console.log(sendRequestUrl);
xmlHttp.open("GET", sendRequestUrl, true); // true for asynchronous
xmlHttp.send(null);
Expand Down Expand Up @@ -133,22 +135,22 @@ function downloadFile(){

if(summfile){
if(filename1){
request1 = baseUrl + "download2/" + 'summary-' + sessionId + '.csv' + "&" +filename1;
request1 = `${baseUrl}download2/${storageFolder}/${sessionId}/summary.csv&${filename1}`;
window.open(request1, '_blank');
}
else{
request1 = baseUrl + "download/" + 'summary-' + sessionId + '.csv';
request1 = `${baseUrl}download/${storageFolder}/${sessionId}/summary.csv`;
window.open(request1, '_blank');
}
}

if(logfile){
if(filename2){
request2 = baseUrl + "download2/" + 'log-' + sessionId + '.csv' + "&" +filename2;
request2 = `${baseUrl}download2/${storageFolder}/${sessionId}/log.csv&${filename2}`;
window.open(request2, '_blank');
}
else{
request2 = baseUrl + "download/" + 'log-' + sessionId + '.csv';
request2 = `${baseUrl}download/${storageFolder}/${sessionId}/log.csv`;
window.open(request2, '_blank');
}
}
Expand Down
8 changes: 6 additions & 2 deletions templates/temp_index.html
Expand Up @@ -72,6 +72,9 @@

<label><abbr title="Number of SYN/ACK Resend Attempts">Number of SynAck resends</abbr>:</label>
<input type="number" id="numbSynAckResends" name="numbSynAckResends" value=3><br>

<label><abbr title="Define your folder to store files generated by simulation">Storage Folder</abbr>:</label>
<input type="text" id="storageFolder" name="storageFolder" value="Unnamed"><br>
</div>


Expand Down Expand Up @@ -455,6 +458,7 @@
document.getElementById("queueLimit").value = queueLimit;
document.getElementById("AtkType").value = attackerType;
document.getElementById("Amp").value = amplification;
document.getElementById("storageFolder").value = storageFolder;

// Conditions to set for different checkboxes.
if(DDDstate == "Yes" || DDDstate =="yes"){
Expand Down Expand Up @@ -553,7 +557,7 @@
<h4 class="text-uppercase m-0">Email</h4>
<hr class="my-4" />
<div class="small text-black-50"><a href="#!">jesse.boog@uconn.edu</a></div>
<div class="small text-black-50"><a href="#!">nhan.nguyen@uconn.com</a></div>
<div class="small text-black-50"><a href="#!">nhan.nguyen@uconn.edu</a></div>
<div class="small text-black-50"><a href="#!">derek.wood@uconn.edu</a></div>
<div class="small text-black-50"><a href="#!">abhinna.adhikari@uconn.edu</a></div>
<div class="small text-black-50"><a href="#!">yaotian.tang@uconn.edu</a></div>
Expand All @@ -575,7 +579,7 @@
</div>
</section>
<!-- Footer-->
<footer class="footer bg-black small text-center text-white-50"><div class="container">Copyright © Your Website 2020</div></footer>
<footer class="footer bg-black small text-center text-white-50"><div class="container">Copyright © UConn CSEGroup22SDP, 2020-2021. All Rights Reserved.</div></footer>
<!-- Bootstrap core JS-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>
Expand Down

0 comments on commit 8ac51c6

Please sign in to comment.