1- from flask import Blueprint , Response , request , jsonify , render_template , flash , redirect , url_for
1+ from flask import Blueprint , Response , request , render_template , flash , redirect , url_for
22from prometheus_client import generate_latest
3+ import os
34
45from src .config import app , db
56from src .models import ExternalMonitornig
67
7-
88# Define the Prometheus Blueprint
99prometheus_bp = Blueprint ('prometheus' , __name__ )
1010
11+
12+ def is_valid_file (file_path : str ) -> bool :
13+ """Checks if a file is valid and have key-value pairs separated by a colon."""
14+ with open (file_path , 'r' ) as file :
15+ for line in file :
16+ if not line .strip ():
17+ continue
18+
19+ if ':' not in line :
20+ return False
21+
22+ return True
23+
1124# Define a route to serve Prometheus metrics
1225@app .route ('/metrics' )
1326def metrics ():
@@ -16,22 +29,32 @@ def metrics():
1629 return Response (output , mimetype = 'text/plain' )
1730
1831# post request to add file path
19- @app .route ('/prometheus/add_file_path ' , methods = ['GET' , 'POST' ])
20- def add_file_path ():
32+ @app .route ('/prometheus/external_monitoring ' , methods = ['GET' , 'POST' ])
33+ def external_monitoring ():
2134 if request .method == 'POST' :
2235
2336 file_path = request .form .get ('file_path' )
37+
38+ if not os .path .exists (file_path ):
39+ flash ('File path does not exist' , 'danger' )
40+ return redirect (url_for ('external_monitoring' ))
41+
42+ # check file path and is_valid
43+ if not is_valid_file (file_path ):
44+ flash ('Invalid file format. File should have key-value pairs separated by a colon.' , 'danger' )
45+ return redirect (url_for ('external_monitoring' ))
46+
2447 # save into the ExternalMonitornig table
2548 new_task = ExternalMonitornig (file_path = file_path )
2649 # commit the changes
2750 db .session .add (new_task )
2851 db .session .commit ()
2952
3053 # read_file_and_update_metric(file_path=file_path)
31- return redirect (url_for ('add_file_path ' ))
54+ return redirect (url_for ('external_monitoring ' ))
3255
3356 data = ExternalMonitornig .query .all ()
34- return render_template ('prometheus/add_file_path .html' , data = data )
57+ return render_template ('prometheus/external_monitoring .html' , data = data )
3558
3659
3760# post request to delete file path
@@ -41,5 +64,5 @@ def delete_file_path(id):
4164 db .session .delete (file_path )
4265 db .session .commit ()
4366 flash ('File path deleted successfully!' , 'success' )
44- return redirect (url_for ('add_file_path ' ))
67+ return redirect (url_for ('external_monitoring ' ))
4568
0 commit comments