-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_manager.py
More file actions
240 lines (204 loc) · 8.01 KB
/
config_manager.py
File metadata and controls
240 lines (204 loc) · 8.01 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
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
import configparser
import os
from pathlib import Path
from cryptography.fernet import Fernet
import json
import logging
from datetime import datetime
from runtime import get_runtime
class ConfigManager:
def __init__(self, runtime=None):
self.runtime = runtime or get_runtime()
self.config_dir = self.runtime.config_dir
self.config_path = self.config_dir / 'config.conf'
self.secrets_path = self.config_dir / '.secrets'
self.key_path = self.config_dir / '.key'
self.alerts_path = self.config_dir / 'alerts.json'
self.config = configparser.ConfigParser()
self.logger = logging.getLogger(__name__)
# Ensure config directory exists
self.config_dir.mkdir(parents=True, exist_ok=True)
# Initialize configuration
self.load_config()
self._init_secrets()
self._init_alerts()
def _init_secrets(self):
"""Initialize the secrets management system"""
if not self.key_path.exists():
key = Fernet.generate_key()
self.key_path.write_bytes(key)
# Set proper permissions
self.key_path.chmod(0o600)
if not self.secrets_path.exists():
self.secrets_path.write_text('{}')
self.secrets_path.chmod(0o600)
self.cipher = Fernet(self.key_path.read_bytes())
def _init_alerts(self):
"""Initialize the alerts storage system"""
if not self.alerts_path.exists():
self.alerts_path.write_text('[]')
self.alerts_path.chmod(0o644)
def load_config(self):
"""Load the configuration file"""
if self.config_path.exists():
self.config.read(self.config_path)
else:
self.create_default_config()
def create_default_config(self):
"""Create default configuration"""
self.config['system'] = {
'username': '',
'server_name': '',
'setup_complete': 'false'
}
self.config['backup'] = {
'email_address': '',
'from_address': '',
'uuid': '',
'usb_id': '',
'mount_point': self.runtime.default_mount_point,
'rclone_dir': '',
'bandwidth_limit': ''
}
self.config['schedule'] = {
'backup_cloud_time': '3:00'
}
self.config['hdsentinel'] = {
'enabled': 'true',
'health_change_alert': 'true'
}
self.save_config()
def save_config(self):
"""Save the configuration to file"""
with open(self.config_path, 'w') as f:
self.config.write(f)
# Set proper permissions
self.config_path.chmod(0o644)
def get_value(self, section, key, default=None):
"""Get a configuration value"""
try:
return self.config.get(section, key)
except (configparser.NoSectionError, configparser.NoOptionError):
return default
def set_value(self, section, key, value):
"""Set a configuration value"""
if not self.config.has_section(section):
self.config.add_section(section)
self.config.set(section, key, str(value))
self.save_config()
def store_secret(self, key, value):
"""Store a sensitive value"""
try:
secrets = json.loads(self.secrets_path.read_text())
encrypted = self.cipher.encrypt(value.encode())
secrets[key] = encrypted.decode()
self.secrets_path.write_text(json.dumps(secrets))
except Exception as e:
self.logger.error(f"Error storing secret: {e}")
raise
def get_secret(self, key, default=None):
"""Retrieve a sensitive value"""
try:
secrets = json.loads(self.secrets_path.read_text())
if key not in secrets:
return default
encrypted = secrets[key].encode()
return self.cipher.decrypt(encrypted).decode()
except Exception as e:
self.logger.error(f"Error retrieving secret: {e}")
return default
def log_alert(self, title, message, alert_type="info", source="system"):
"""Log an alert to the alerts file"""
try:
alerts = self.get_alerts()
alert = {
'id': len(alerts) + 1,
'title': title,
'message': message,
'type': alert_type,
'source': source,
'timestamp': datetime.now().isoformat(),
'read': False
}
alerts.append(alert)
# Keep only the last 1000 alerts to prevent file from growing too large
if len(alerts) > 1000:
alerts = alerts[-1000:]
self.alerts_path.write_text(json.dumps(alerts, indent=2))
self.logger.info(f"Alert logged: {title}")
return True
except Exception as e:
self.logger.error(f"Error logging alert: {e}")
return False
def get_alerts(self, limit=None, unread_only=False):
"""Get alerts from the alerts file"""
try:
if not self.alerts_path.exists():
return []
alerts = json.loads(self.alerts_path.read_text())
if unread_only:
alerts = [alert for alert in alerts if not alert.get('read', False)]
if limit:
alerts = alerts[-limit:]
return alerts
except Exception as e:
self.logger.error(f"Error reading alerts: {e}")
return []
def mark_alert_read(self, alert_id):
"""Mark an alert as read"""
try:
alerts = self.get_alerts()
for alert in alerts:
if alert['id'] == alert_id:
alert['read'] = True
break
self.alerts_path.write_text(json.dumps(alerts, indent=2))
return True
except Exception as e:
self.logger.error(f"Error marking alert as read: {e}")
return False
def clear_alerts(self):
"""Clear all alerts"""
try:
self.alerts_path.write_text('[]')
self.logger.info("All alerts cleared")
return True
except Exception as e:
self.logger.error(f"Error clearing alerts: {e}")
return False
def mark_all_alerts_read(self):
"""Mark all alerts as read"""
try:
alerts = self.get_alerts()
for alert in alerts:
alert['read'] = True
self.alerts_path.write_text(json.dumps(alerts, indent=2))
return True
except Exception as e:
self.logger.error(f"Error marking all alerts as read: {e}")
return False
def is_setup_complete(self):
"""Check if initial setup is complete; always reload config to ensure freshness"""
self.load_config()
return self.get_value('system', 'setup_complete', 'false').lower() == 'true'
def mark_setup_complete(self):
"""Mark the initial setup as complete"""
self.set_value('system', 'setup_complete', 'true')
def get_all_config(self):
"""Get all non-sensitive configuration"""
config_dict = {}
for section in self.config.sections():
config_dict[section] = dict(self.config[section])
return config_dict
def validate_config(self):
"""Validate the current configuration"""
required_fields = {
'system': ['username', 'server_name'],
'backup': ['email_address', 'uuid', 'usb_id', 'mount_point', 'rclone_dir']
}
missing_fields = []
for section, fields in required_fields.items():
for field in fields:
if not self.get_value(section, field):
missing_fields.append(f"{section}.{field}")
return len(missing_fields) == 0, missing_fields