-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessen.py
More file actions
176 lines (147 loc) · 5.89 KB
/
messen.py
File metadata and controls
176 lines (147 loc) · 5.89 KB
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
import requests
from bs4 import BeautifulSoup
import mysql.connector
import csv
import time
import threading
import keyboard
import sys
baseIP = "139.6.65.27"
db1Config = {
"host": baseIP,
"port": 31006,
"user": "wfc",
"password": "wfc",
"database": "times"
}
db2Config = {
"host": baseIP,
"port": 31007,
"user": "wfc",
"password": "wfc",
"database": "maps"
}
rabbitmqUser = "guest"
rabbitmqPassword = "guest"
rabbitmqQueue = "maptickets"
rabbitmqApiUrl = f"http://{baseIP}:31672/api/queues/%2F/{rabbitmqQueue}"
def isQueueEmpty():
try:
response = requests.get(rabbitmqApiUrl, auth=(rabbitmqUser, rabbitmqPassword))
if response.ok:
data = response.json()
messages = data.get("messages", -1)
print(f"Queue '{rabbitmqQueue}' has {messages} messages.")
return messages == 0
else:
print(f"Failed to get queue status: {response.status_code} {response.text}")
return False
except Exception as e:
print(f"Error checking RabbitMQ queue: {e}")
return False
numberOfWorkers = int(sys.argv[1])
csvPath = "messreihen.csv"
uuidColumnName = "uuid"
dbValueColumnName = "total"
statusPollInterval = 5
maxWaitTime = 1200
exitRequested = False
immediateExitRequested = False
def watchForExit():
global exitRequested
print("Press 'X' to stop the script gracefully.")
keyboard.wait("x")
print("\nExit requested. Finishing current row and saving...")
exitRequested = True
def watchForImmediateExit():
global immediateExitRequested
print("Press 'Q' to stop the script gracefully immediately.")
keyboard.wait("q")
print("\nExit requested. saving ...")
immediateExitRequested = True
threading.Thread(target=watchForExit, daemon=True).start()
threading.Thread(target=watchForImmediateExit, daemon=True).start()
updatedRows = []
with open(csvPath, mode="r", newline="") as file:
reader = csv.reader(file)
headers = next(reader)
if uuidColumnName not in headers:
headers.append(uuidColumnName)
if dbValueColumnName not in headers:
headers.append(dbValueColumnName)
for rowIndex, row in enumerate(reader, start=1):
if exitRequested:
updatedRows.append(row)
break
print("Row: ", row)
if int(row[2]) == numberOfWorkers and (len(row) < 7 or row[6].strip() == ""):
payload = {
"var1": str(row[0]),
"var2": str(row[1]),
"var3": "0",
"var4": str(row[2])
}
response = requests.post(f"http://{baseIP}:31000/setRules", data=payload)
time.sleep(30)
try:
response = requests.post(f"http://{baseIP}:31001/mapGenerator")
if response.ok:
soup = BeautifulSoup(response.text, "html.parser")
uuidTag = soup.h1
uuid = uuidTag.text.strip() if uuidTag else ""
else:
uuid = ""
except Exception as e:
print(f"Error during POST for row {rowIndex}: {e}")
uuid = ""
dbValue = ""
if uuid:
startTime = time.time()
while True:
if immediateExitRequested:
break
try:
conn2 = mysql.connector.connect(**db2Config)
cursor2 = conn2.cursor()
cursor2.execute("SELECT mapID FROM mapchunks WHERE mapID = %s GROUP BY mapID HAVING SUM(CASE WHEN computed IS NOT TRUE THEN 1 ELSE 0 END) = 0", (uuid,))
statusResult = cursor2.fetchone()
cursor2.close()
conn2.close()
if statusResult:
print(f"Computation complete for UUID {uuid}")
print("Waiting for RabbitMQ queue to empty...")
while not isQueueEmpty():
if immediateExitRequested:
break
time.sleep(5)
print("RabbitMQ queue is empty. Continuing...")
break
except mysql.connector.Error as err:
print(f"MySQL error (status DB) for UUID {uuid}: {err}")
time.sleep(statusPollInterval)
try:
conn1 = mysql.connector.connect(**db1Config)
cursor1 = conn1.cursor()
cursor1.execute("SELECT totalDuration FROM mapTimes WHERE mapID = %s LIMIT 1", (uuid,))
result = cursor1.fetchone()
dbValue = result[0] if result else ""
cursor1.close()
conn1.close()
except mysql.connector.Error as err:
print(f"MySQL error (main DB) for UUID {uuid}: {err}")
dbValue = ""
if immediateExitRequested:
updatedRows.append(row)
break
while len(row) < len(headers):
row.append("")
row[headers.index(uuidColumnName)] = uuid
row[headers.index(dbValueColumnName)] = dbValue
updatedRows.append(row)
for remainingRow in reader:
updatedRows.append(remainingRow)
with open(csvPath, mode="w", newline="") as file:
writer = csv.writer(file)
writer.writerow(headers)
writer.writerows(updatedRows)
print("CSV fully processed.")