-
Notifications
You must be signed in to change notification settings - Fork 5
/
em_code.py
303 lines (257 loc) · 9.8 KB
/
em_code.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
"""Task source code handler."""
import re
import urllib.parse
from typing import Optional
import requests
import urllib3
from flask import current_app as app
from runner.extensions import db
from runner.model import Task
from runner.scripts.em_messages import RunnerException, RunnerLog
from runner.scripts.em_params import ParamLoader
urllib3.disable_warnings()
class SourceCode:
"""Group of functions used to get various type of source code for task runner."""
def __init__(
self,
task: Task,
run_id: Optional[str],
params: ParamLoader,
refresh_cache: Optional[bool] = False,
) -> None:
"""Set up class parameters."""
self.task = task
self.run_id = run_id
self.params = params
self.db_type = (
"mssql"
if self.task.source_database_conn
and self.task.source_database_conn.type_id == 2
else None
)
self.query: str = ""
self.refresh_cache = refresh_cache
def gitlab(self, url: str) -> str:
"""Get source code from gitlab using authentication."""
# pylint: disable=too-many-statements
if ".git" in str(url):
return ""
if url:
try:
# convert the "raw" url into an api url
branch = urllib.parse.quote(
urllib.parse.unquote(
re.findall(r"\/(?:raw|blob)\/(.+?)\/", url)[0]
),
safe="",
)
project = urllib.parse.quote(
urllib.parse.unquote(
re.findall(r"\.(?:com|net|org)\/(.+?)\/-", url)[0]
),
safe="",
)
file_path = urllib.parse.quote(
urllib.parse.unquote(
re.findall(r"\/(?:raw|blob)\/.+?\/(.+?)$", url)[0]
),
safe="",
)
api_url = "%sapi/v4/projects/%s/repository/files/%s/raw?ref=%s" % (
app.config["GIT_URL"],
project,
file_path,
branch,
)
headers = {"PRIVATE-TOKEN": app.config["GIT_TOKEN"]}
page = requests.get(
api_url, verify=False, headers=headers
) # noqa: S501
if page.status_code != 200:
raise Exception("Failed to get code: " + page.text)
if url.lower().endswith(".sql"):
self.query = page.text
self.db_type = (
"mssql"
if self.task.source_database_conn
and self.task.source_database_conn.type_id == 2
else None
)
# save query cache before cleanup.
if self.run_id or self.refresh_cache:
self.task.source_cache = self.query
db.session.commit()
if self.refresh_cache:
RunnerLog(
self.task,
self.run_id,
15,
"Source cache manually refreshed.",
)
# insert params
return self.cleanup()
return (
page.text
if not page.text.startswith("<!DOCTYPE")
else "Visit URL to view code"
)
# pylint: disable=broad-except
except BaseException as e:
# only use cache if we have a run id. Otherwise failures are from code preview.
if (
self.run_id
and self.task.enable_source_cache == 1
and self.task.source_cache
):
RunnerLog(
self.task,
self.run_id,
15,
f"Failed to get source from {url}. Using cached query.\nFull trace:\n{e}",
)
self.db_type = (
"mssql"
if self.task.source_database_conn
and self.task.source_database_conn.type_id == 2
else None
)
self.query = self.task.source_cache
return self.cleanup()
elif (
self.run_id
and self.task.enable_source_cache == 1
and not self.task.source_cache
):
raise RunnerException(
self.task,
self.run_id,
15,
f"Failed to get source from {url}. Cache enabled, but no cache available.\n{e}",
)
else:
raise RunnerException(
self.task,
self.run_id,
15,
f"Failed to get source from {url}.\n{e}",
)
raise RunnerException(
self.task, self.run_id, 15, "No url specified to get source from."
)
def web_url(self, url: str) -> str:
"""Get contents of a webpage."""
try:
page = requests.get(str(url), verify=False) # noqa: S501
self.query = page.text
self.db_type = (
"mssql"
if self.task.source_database_conn
and self.task.source_database_conn.type_id == 2
else None
)
if page.status_code != 200:
raise ValueError(f"{url} returned bad status: {page.status_code}")
# save query cache before cleanup.
if self.run_id or self.refresh_cache:
self.task.source_cache = self.query
db.session.commit()
if self.refresh_cache:
RunnerLog(
self.task, self.run_id, 15, "Source cache manually refreshed."
)
# insert params
return self.cleanup()
# pylint: disable=broad-except
except BaseException as e:
if (
self.run_id
and self.task.enable_source_cache == 1
and self.task.source_cache
):
RunnerLog(
self.task,
self.run_id,
15,
f"Failed to get source from {url}. Using cached query.\nFull trace:\n{e}",
)
self.db_type = (
"mssql"
if self.task.source_database_conn
and self.task.source_database_conn.type_id == 2
else None
)
self.query = self.task.source_cache
return self.cleanup()
elif (
self.run_id
and self.task.enable_source_cache == 1
and not self.task.source_cache
):
raise RunnerException(
self.task,
self.run_id,
15,
f"Failed to get source from {url}. Cache enabled, but no cache available.\n{e}",
)
else:
raise RunnerException(
self.task, self.run_id, 15, f"Failed to get source from {url}\n{e}."
)
def source(self, query: Optional[str] = None) -> str:
"""Get task source code."""
try:
self.query = query or self.task.source_code or ""
self.db_type = (
"mssql"
if self.task.source_database_conn
and self.task.source_database_conn.type_id == 2
else None
)
return self.cleanup()
# pylint: disable=broad-except
except BaseException as e:
raise RunnerException(
self.task, self.run_id, 15, f"Failed to clean source code.\n{e}."
)
def cleanup(self, query: Optional[str] = None) -> str:
"""Clean up source code.
:param str query: query to clean
:param str db_type: sql query language name
:param list task_params: list of task level sql parameters to be injected
:param list project_params: list of project level sql parameters to be injected
:returns: Cleaned up query.
"""
# remove database call
# sql stuff
query = query or self.query
# only needed for mssql
if self.task.source_type_id == 1 and self.db_type == "mssql":
query = re.sub(
re.compile(
r"(^;?\s*;?)\buse\b\s+.+", flags=re.IGNORECASE | re.MULTILINE
),
"",
query,
)
query = re.sub(
re.compile(
r"(^;?\s*;?)\buse\b\s+.+?;", flags=re.IGNORECASE | re.MULTILINE
),
"",
query,
)
# add no count
query = "SET NOCOUNT ON;\n" + query
# disable warnings
query = "SET ANSI_WARNINGS OFF;\n" + query
query = "SET STATISTICS IO OFF;\n" + query
query = "SET STATISTICS TIME OFF;\n" + query
# remove " go"
query = re.sub(
re.compile(
r"^;?\s*?;?\bgo\b\s*?;?", flags=re.IGNORECASE | re.MULTILINE
),
r"",
query,
)
return self.params.insert_query_params(query)