Skip to content

Commit 1943394

Browse files
sqlite replaced with prometheus for time series metrics
1 parent 1b96a86 commit 1943394

11 files changed

Lines changed: 408 additions & 171 deletions

File tree

app.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,10 @@
44
import os
55

66
# background thread to monitor system settings changes
7-
# print("FLASK_ENV: ", os.getenv('FLASK_ENV'))
8-
# # if os.getenv('FLASK_ENV') == 'production':
9-
# start_website_monitoring() # Starts pinging active websites
10-
# fetch_file_metrics_task()
11-
monitor_settings() # Starts monitoring for system logging changes
7+
if os.getenv('FLASK_ENV') == 'production':
8+
start_website_monitoring() # Starts pinging active websites
9+
fetch_file_metrics_task()
10+
monitor_settings() # Starts monitoring for system logging changes
1211

1312
if __name__ == "__main__":
1413
app.run(host="0.0.0.0", port=5000, debug=True)

prometheus_config/prometheus.yml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
global:
2+
scrape_interval: 30s # How often Prometheus scrapes the target
3+
4+
scrape_configs:
5+
- job_name: 'flask_app_metrics' # Scraping metrics from Flask app
6+
static_configs:
7+
- targets: ['192.168.1.10:5050']

setup.sh

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -853,10 +853,12 @@ start_server() {
853853

854854
# Install function
855855
install() {
856+
create_dir "$EXTRACT_DIR"
857+
# PROMETHEUS_INSTALL_SCRIPT
856858
message_box "$APP_NAME Installer $INSATLLER_VERSION" 0
857859
message_box "Welcome on board: $(echo "$USER_NAME" | sed 's/.*/\u&/')" 3
858860
check_dependencies
859-
create_dir "$EXTRACT_DIR"
861+
860862
message_box "Choose the installation method\nNote: Release is recommended for production use." 0
861863
message_box "1. Release (More Stable Version)\n2. Git Repository (Pre-Release Version)\n3. Source Code (Current Directory)" 0
862864

@@ -878,6 +880,11 @@ install() {
878880
exit 1
879881
;;
880882
esac
883+
PROMETHEUS_INSTALL_SCRIPT=$(find "$EXTRACT_DIR" -name prometheus.sh) || {
884+
log "ERROR" "Prometheus installation script not found."
885+
exit 1
886+
}
887+
sudo -u "$USER_NAME" bash "$PROMETHEUS_INSTALL_SCRIPT"
881888
start_server
882889
message_box "The $APP_NAME server is running at $HOST_URL" 0
883890
# open_browser

src/background_task/log_system_info.py

Lines changed: 35 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@
88
from sqlalchemy.exc import SQLAlchemyError
99
from prometheus_client import Counter, Gauge
1010
import os, time
11-
from influxdb_client import Point, WritePrecision
1211

1312
from src.logger import logger
14-
from src.config import influx_client, bucket, write_api
13+
from src.influxdb_config import bucket, write_api
14+
from src.utils import get_system_username
1515
# Flag to track if logging is already scheduled
1616
is_logging_scheduled = False
17+
fetch_system_info_interval = 30
1718

1819
# Initialize Prometheus metrics
1920
metrics = {
@@ -44,7 +45,7 @@ def log_system_info():
4445

4546
log_system_info_to_db()
4647
logger.debug("System information logged successfully.")
47-
schedule_next_log()
48+
schedule_next_log(interval=fetch_system_info_interval)
4849

4950
except Exception as e:
5051
logger.error(f"Error during system info logging: {e}", exc_info=True)
@@ -63,7 +64,7 @@ def is_logging_enabled():
6364
return False
6465

6566

66-
def schedule_next_log(interval=60):
67+
def schedule_next_log(interval=10):
6768
"""
6869
Schedules the next logging event after the specified interval (in seconds).
6970
"""
@@ -80,8 +81,9 @@ def log_system_info_to_db():
8081

8182
# Update Prometheus metrics
8283
update_prometheus_metrics(system_info)
84+
8385
# Store system information in InfluxDB
84-
store_system_info_in_influxdb(system_info)
86+
# store_system_info_in_influxdb(system_info)
8587

8688
# Store system information in the database
8789
# store_system_info_in_db(system_info)
@@ -128,34 +130,34 @@ def store_system_info_in_db(system_info):
128130
db.session.add(system_log)
129131
db.session.commit()
130132

131-
def store_system_info_in_influxdb(system_info):
132-
"""
133-
Stores the collected system information into the InfluxDB with proper error handling.
134-
"""
135-
try:
136-
# Create a data point for system information
137-
point = (
138-
Point("system_info")
139-
.tag("host", os.environ.get("HOSTNAME", "unknown"))
140-
.field("cpu_percent", system_info["cpu_percent"])
141-
.field("memory_percent", system_info["memory_percent"])
142-
.field("battery_percent", system_info["battery_percent"])
143-
.field("network_sent", system_info["network_sent"])
144-
.field("network_received", system_info["network_received"])
145-
.field("dashboard_memory_usage", system_info["dashboard_memory_usage"])
146-
.field("cpu_frequency", system_info["cpu_frequency"])
147-
.field("current_temp", system_info["current_temp"])
148-
.time(int(time.time() * 1_000_000_000), WritePrecision.NS) # Nanosecond precision
149-
)
150-
151-
# Write the data point to InfluxDB
152-
write_api.write(bucket=bucket, record=point)
153-
logger.info("Successfully wrote system information to InfluxDB")
154-
155-
except ValueError as ve:
156-
logger.error(f"Value error while storing system info: {ve}")
157-
except Exception as e:
158-
logger.error(f"An unexpected error occurred: {e}", exc_info=True)
133+
# def store_system_info_in_influxdb(system_info):
134+
# """
135+
# Stores the collected system information into the InfluxDB with proper error handling.
136+
# """
137+
# try:
138+
# # Create a data point for system information
139+
# point = (
140+
# Point("system_info")
141+
# .tag("host", get_system_username())
142+
# .field("cpu_percent", system_info["cpu_percent"])
143+
# .field("memory_percent", system_info["memory_percent"])
144+
# .field("battery_percent", system_info["battery_percent"])
145+
# .field("network_sent", system_info["network_sent"])
146+
# .field("network_received", system_info["network_received"])
147+
# .field("dashboard_memory_usage", system_info["dashboard_memory_usage"])
148+
# .field("cpu_frequency", system_info["cpu_frequency"])
149+
# .field("current_temp", system_info["current_temp"])
150+
# .time(int(time.time() * 1_000_000_000))
151+
# )
152+
153+
# # Write the data point to InfluxDB
154+
# write_api.write(bucket=bucket, record=point)
155+
# logger.info("Successfully wrote system information to InfluxDB")
156+
157+
# except ValueError as ve:
158+
# logger.error(f"Value error while storing system info: {ve}")
159+
# except Exception as e:
160+
# logger.error(f"An unexpected error occurred: {e}", exc_info=True)
159161

160162

161163

src/config.py

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -39,26 +39,6 @@
3939
db = SQLAlchemy(app)
4040
migrate = Migrate(app, db)
4141

42-
# influx db configuration
43-
44-
INFLUXDB_TOKEN=""
45-
print("Token: ", INFLUXDB_TOKEN)
46-
if not INFLUXDB_TOKEN:
47-
raise ValueError("Please set the INFLUXDB_TOKEN environment variable.")
48-
org = "systemguard"
49-
url = "http://localhost:8086"
50-
bucket="system_metrics"
51-
try:
52-
influx_client = InfluxDBClient(url=url, token=INFLUXDB_TOKEN, org=org)
53-
bucket = "system_metrics"
54-
write_api = influx_client.write_api(write_options=SYNCHRONOUS)
55-
query_api = influx_client.query_api()
56-
logger.info("Connected to InfluxDB successfully")
57-
58-
except Exception as e:
59-
logger.error(f"Failed to connect to InfluxDB: {e}")
60-
raiseclient = InfluxDBClient(url=url, token=INFLUXDB_TOKEN, org=org)
61-
6242
# Define global variables for templates
6343
app.jinja_env.globals.update(
6444
title=APP_NAME,

src/helper.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,7 @@ def get_ip_address():
3333

3434
return ip_address
3535
except (IndexError, subprocess.CalledProcessError) as e:
36-
print(f"Error occurred: {e}")
3736
return None
38-
39-
40-
import os
41-
import subprocess
4237

4338
def check_installation_information():
4439
# Output dictionary to store results
@@ -82,7 +77,6 @@ def check_installation_information():
8277
# Check for updates
8378
try:
8479
result = subprocess.run(["git", "status", "-uno"], capture_output=True, text=True, check=True)
85-
print(result.stdout)
8680
if "Your branch is up to date" in result.stdout:
8781
output["update_available"] = False
8882
else:

src/influxdb_config.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from influxdb_client import InfluxDBClient, Point, WritePrecision
2+
from influxdb_client.client.write_api import SYNCHRONOUS
3+
import os
4+
from src.logger import logger
5+
6+
7+
# influx db configuration
8+
org = "systemguard"
9+
url = "http://localhost:8086"
10+
bucket="system_metrics"
11+
INFLUXDB_TOKEN=os.getenv('INFLUXDB_TOKEN')
12+
print("INFLUXDB_TOKEN: ", INFLUXDB_TOKEN)
13+
14+
try:
15+
influx_client = InfluxDBClient(url=url, token=INFLUXDB_TOKEN, org=org)
16+
bucket = "system_metrics"
17+
write_api = influx_client.write_api(write_options=SYNCHRONOUS)
18+
query_api = influx_client.query_api()
19+
logger.info("Connected to InfluxDB successfully")
20+
except Exception as e:
21+
logger.error(f"Failed to connect to InfluxDB: {e}")
22+
raiseclient = InfluxDBClient(url=url, token=INFLUXDB_TOKEN, org=org)

0 commit comments

Comments
 (0)