forked from agessaman/meshinfo-lite
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_docker.py
More file actions
209 lines (170 loc) · 6.62 KB
/
setup_docker.py
File metadata and controls
209 lines (170 loc) · 6.62 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
#!/usr/bin/env python3
"""
Docker Setup Script for MeshInfo-Lite
This script sets up the database with proper privileges for Docker Compose installations.
It should be run after the Docker containers are started.
Usage:
python setup_docker.py
Requirements:
- Docker Compose services running
- config.ini file with database configuration
"""
import configparser
import mysql.connector
import logging
import sys
import os
import time
def setup_logging():
"""Setup basic logging for the setup script."""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
def check_config():
"""Check if config.ini exists and has required database settings."""
if not os.path.exists('config.ini'):
logging.error("config.ini not found! Please create it first.")
return False
config = configparser.ConfigParser()
config.read('config.ini')
required_sections = ['database']
required_keys = ['host', 'username', 'password', 'database']
for section in required_sections:
if section not in config:
logging.error(f"Missing [{section}] section in config.ini")
return False
for key in required_keys:
if key not in config[section]:
logging.error(f"Missing {key} in [{section}] section of config.ini")
return False
return True
def wait_for_database(config, max_attempts=30):
"""Wait for the database to become available."""
logging.info("Waiting for database to become available...")
for attempt in range(max_attempts):
try:
# Try to connect as root first
root_password = config.get("database", "root_password", fallback="passw0rd")
db = mysql.connector.connect(
host=config["database"]["host"],
user="root",
password=root_password,
connection_timeout=5
)
db.close()
logging.info("✓ Database is available")
return True
except mysql.connector.Error as e:
if attempt < max_attempts - 1:
logging.info(f"Database not ready yet (attempt {attempt + 1}/{max_attempts})...")
time.sleep(2)
else:
logging.error(f"Database failed to become available: {e}")
return False
return False
def setup_database_privileges(config):
"""Set up database privileges for the application user."""
root_password = config.get("database", "root_password", fallback="passw0rd")
try:
# Connect as root
db = mysql.connector.connect(
host=config["database"]["host"],
user="root",
password=root_password,
)
logging.info("Setting up database privileges...")
# Grant RELOAD privilege for query cache operations
cur = db.cursor()
cur.execute(f"""GRANT RELOAD ON *.* TO '{config["database"]["username"]}'@'%'""")
cur.close()
logging.info("✓ Granted RELOAD privilege for query cache operations")
# Grant PROCESS privilege for monitoring
cur = db.cursor()
cur.execute(f"""GRANT PROCESS ON *.* TO '{config["database"]["username"]}'@'%'""")
cur.close()
logging.info("✓ Granted PROCESS privilege for monitoring")
# Flush privileges to apply changes
cur = db.cursor()
cur.execute("FLUSH PRIVILEGES")
cur.close()
logging.info("✓ Privileges flushed")
db.commit()
db.close()
logging.info("✓ Database privileges setup completed successfully!")
return True
except mysql.connector.Error as e:
logging.error(f"Error setting up database privileges: {e}")
return False
def test_user_connection(config):
"""Test connection with the application user."""
try:
db = mysql.connector.connect(
host=config["database"]["host"],
user=config["database"]["username"],
password=config["database"]["password"],
database=config["database"]["database"],
)
db.close()
logging.info("✓ Successfully connected with application user")
return True
except mysql.connector.Error as e:
logging.error(f"Failed to connect with application user: {e}")
return False
def test_privileges(config):
"""Test if the user has the required privileges."""
try:
db = mysql.connector.connect(
host=config["database"]["host"],
user=config["database"]["username"],
password=config["database"]["password"],
database=config["database"]["database"],
)
cur = db.cursor()
# Test RELOAD privilege
try:
cur.execute("FLUSH QUERY CACHE")
logging.info("✓ RELOAD privilege verified")
except mysql.connector.Error as e:
logging.warning(f"RELOAD privilege test failed: {e}")
# Test PROCESS privilege
try:
cur.execute("SHOW PROCESSLIST")
logging.info("✓ PROCESS privilege verified")
except mysql.connector.Error as e:
logging.warning(f"PROCESS privilege test failed: {e}")
cur.close()
db.close()
return True
except mysql.connector.Error as e:
logging.error(f"Error testing privileges: {e}")
return False
def main():
"""Main setup function."""
setup_logging()
logging.info("=== MeshInfo-Lite Docker Setup ===")
# Check configuration
if not check_config():
sys.exit(1)
config = configparser.ConfigParser()
config.read('config.ini')
# Wait for database to become available
if not wait_for_database(config):
logging.error("Database is not available. Please ensure Docker Compose services are running.")
logging.error("Run: docker-compose up -d")
sys.exit(1)
# Set up database privileges
if not setup_database_privileges(config):
sys.exit(1)
# Test user connection
if not test_user_connection(config):
logging.error("Setup completed but user connection test failed")
sys.exit(1)
# Test privileges
test_privileges(config)
logging.info("=== Docker Setup Complete ===")
logging.info("The MeshInfo-Lite application should now have full functionality")
logging.info("Check the application logs for any remaining issues")
if __name__ == "__main__":
main()