-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJenkinsfile
285 lines (245 loc) · 9.88 KB
/
Jenkinsfile
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
pipeline {
agent any
environment {
VENV_NAME = 'endpoint-extractor-venv'
MONGO_USER = credentials('mongo-user')
MONGO_PASS = credentials('mongo-pass')
MONGO_URI = credentials('mongo-uri')
}
parameters {
string(name: 'TARGET_URL', defaultValue: 'https://54.165.189.43/active', description: 'The URL to send the GET request to')
string(name: 'TARGET_VALUE', defaultValue: 'http://4.240.48.35:4444', description: 'The value for the "target" key in the JSON body')
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Setup Python') {
steps {
sh """
python3 -m venv ${VENV_NAME}
. ${VENV_NAME}/bin/activate
pip install --upgrade pip
pip install pymongo pyyaml requests
"""
}
}
stage('Process Endpoints') {
steps {
script {
writeFile file: 'process_endpoints.py', text: '''
import ast
import yaml
import re
import os
def extract_docstring(node):
"""Extract the docstring from a function node."""
return ast.get_docstring(node)
def parse_openapi_comment(comment):
"""Parse the YAML content from a docstring comment."""
comment = comment.strip('"""').strip()
try:
return yaml.safe_load(comment)
except yaml.YAMLError as e:
print(f"Error parsing YAML content: {e}")
return None
def extract_route_info(decorator):
"""Extract route information from a decorator."""
route_info = {'path': None, 'methods': []}
if isinstance(decorator, ast.Call) and isinstance(decorator.func, ast.Attribute):
if decorator.func.attr == 'route':
if decorator.args:
route_info['path'] = decorator.args[0].s
for keyword in decorator.keywords:
if keyword.arg == 'methods':
if isinstance(keyword.value, ast.List):
route_info['methods'] = [elt.s for elt in keyword.value.elts]
elif decorator.func.attr in ['get', 'post', 'put', 'delete', 'patch']:
if decorator.args:
route_info['path'] = decorator.args[0].s
route_info['methods'] = [decorator.func.attr.upper()]
return route_info
def extract_endpoints(source_code):
"""Extract endpoints and their details from source code."""
tree = ast.parse(source_code)
endpoints = []
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
docstring = extract_docstring(node)
if docstring and '---' in docstring:
endpoint_info = parse_openapi_comment(docstring)
if endpoint_info:
for decorator in node.decorator_list:
route_info = extract_route_info(decorator)
if route_info['path']:
endpoint_info['path'] = route_info['path']
endpoint_info['methods'] = route_info['methods']
endpoints.append(endpoint_info)
return endpoints
def parse_path_parameters(path):
"""Parse path parameters from the path string."""
path_params = re.findall(r'<(?:(?:string|int|float|path):)?(\\w+)>', path)
return path_params
def generate_openapi_spec(endpoints, info):
"""Generate an OpenAPI specification from endpoints."""
openapi_spec = {
"openapi": "3.0.0",
"info": info,
"paths": {}
}
for endpoint in endpoints:
path = endpoint.get("path", "/")
methods = endpoint.get("methods", ["GET"])
# Replace Flask-style path parameters with OpenAPI style
path_params = parse_path_parameters(path)
if path_params:
for param in path_params:
path = path.replace(f'<{param}>', f'{{{param}}}')
path = path.replace(f'<int:{param}>', f'{{{param}}}')
path = path.replace(f'<float:{param}>', f'{{{param}}}')
path = path.replace(f'<string:{param}>', f'{{{param}}}')
path = path.replace(f'<path:{param}>', f'{{{param}}}')
if path not in openapi_spec["paths"]:
openapi_spec["paths"][path] = {}
for method in methods:
method = method.lower()
if method not in openapi_spec["paths"][path]:
openapi_spec["paths"][path][method] = {
"summary": endpoint.get("summary"),
"description": endpoint.get("description"),
"parameters": [],
"responses": endpoint.get("responses", {})
}
# Add path parameters if they're not already specified
existing_param_names = [p['name'] for p in openapi_spec["paths"][path][method]["parameters"] if p['in'] == 'path']
for param in path_params:
if param not in existing_param_names:
openapi_spec["paths"][path][method]["parameters"].append({
"name": param,
"in": "path",
"required": True,
"schema": {"type": "string"}
})
return openapi_spec
def process_directory(directory):
"""Process all Python files in the directory to extract endpoints."""
all_endpoints = []
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.py'):
file_path = os.path.join(root, file)
with open(file_path, 'r') as file:
source_code = file.read()
endpoints = extract_endpoints(source_code)
all_endpoints.extend(endpoints)
return all_endpoints
def main(directory, output_path):
"""Main function to process files and generate OpenAPI specification."""
endpoints = process_directory(directory)
info = {
"title": "Grid_Testing",
"version": "1.0.0",
"description": "APIs"
}
openapi_spec = generate_openapi_spec(endpoints, info)
with open(output_path, 'w') as file:
yaml.dump(openapi_spec, file, sort_keys=False)
print(f"OpenAPI specification has been generated and saved to {output_path}")
if __name__ == "__main__":
directory = "." # Default to current directory
output_path = "endpoints.yaml"
main(directory, output_path)
'''
// Create a Python script to process endpoints and save to MongoDB
writeFile file: 'save_to_db.py', text: '''
import os
import yaml
from pymongo import MongoClient
import sys
# Get MongoDB credentials and connection info from command line arguments
username = sys.argv[1]
password = sys.argv[2]
cluster = sys.argv[3]
mongo_uri = "mongodb+srv://" + username + ":" + password + cluster
client = MongoClient(mongo_uri)
db = client['endpoints_db']
collection = db['endpoints']
def process_endpoints(root_dir):
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith('.yaml') or file.endswith('.yml'):
file_path = os.path.join(root, file)
with open(file_path, 'r') as f:
try:
openapi_data = yaml.safe_load(f)
paths = openapi_data.get('paths', {})
for path, methods in paths.items():
endpoint_record = {
'path': path,
'methods': []
}
for method, details in methods.items():
method_record = {
'method': method.upper(),
'description': details.get('description', ''),
'parameters': details.get('parameters', []),
'responses': details.get('responses', {}),
}
method_record['responses'] = {str(key): value for key, value in method_record['responses'].items()}
endpoint_record['methods'].append(method_record)
collection.update_one(
{
'path': path
},
{'$set': endpoint_record},
upsert=True
)
except yaml.YAMLError as e:
continue
print(f"Processed: {file_path}")
if __name__ == "__main__":
process_endpoints('.')
print("Endpoint processing completed.")
'''
writeFile file: 'send_request.py', text: '''
import requests
def send_request():
url = "http://54.165.189.43:8000/active"
headers = {
"Content-Type": "application/json"
}
data = {
"target": "http://4.240.48.35:4444"
}
try:
requests.post(url, json=data, headers=headers, timeout=5)
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
send_request()
'''
// Run the Python script
sh """
. ${VENV_NAME}/bin/activate
python3 process_endpoints.py
python3 save_to_db.py '${MONGO_USER}' '${MONGO_PASS}' '${MONGO_URI}'
python3 send_request.py
"""
}
}
}
}
post {
always {
// Clean up
sh """
rm -rf ${VENV_NAME}
rm process_endpoints.py
rm save_to_db.py
rm send_request.py
"""
}
}
}