-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
294 lines (246 loc) · 8.51 KB
/
main.js
File metadata and controls
294 lines (246 loc) · 8.51 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
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
286
287
288
289
290
291
292
293
294
const { Worker } = require('worker_threads');
const path = require('path');
const fs = require('fs').promises;
const EventEmitter = require('events');
const ConfigManager = require('./config-manager');
class OneStackServer extends EventEmitter {
constructor() {
super();
this.modules = new Map();
this.availableModules = new Map(); // Track all available modules
this.configManager = new ConfigManager('./config.json');
this.config = null;
this.apiServer = null;
// Listen to config changes
this.configManager.on('updated', (config, updates) => {
this.emit('configUpdated', config, updates);
console.log('Configuration updated');
});
}
/**
* Discover all available modules in the modules directory
*/
async discoverModules() {
try {
const modulesDir = path.join(__dirname, 'modules');
const files = await fs.readdir(modulesDir);
for (const file of files) {
if (file.endsWith('.js') && file !== 'base_module.js' && !file.startsWith('_')) {
const moduleName = file.replace('.js', '');
const modulePath = path.join(modulesDir, file);
try {
// Try to load module class
const ModuleClass = require(modulePath);
// Get module metadata if available
const metadata = {
name: moduleName,
path: modulePath,
class: ModuleClass,
description: ModuleClass.description || `${moduleName} module`,
version: ModuleClass.version || '1.0.0',
author: ModuleClass.author || 'Unknown'
};
this.availableModules.set(moduleName, metadata);
console.log(` ✓ Discovered: ${moduleName}`);
} catch (error) {
console.error(` ✗ Failed to discover ${moduleName}:`, error.message);
}
}
}
console.log(`Found ${this.availableModules.size} available modules`);
} catch (error) {
console.error('Failed to discover modules:', error.message);
}
}
/**
* Get list of all available modules
*/
getAvailableModules() {
const modules = [];
for (const [name, metadata] of this.availableModules) {
modules.push({
name,
description: metadata.description,
version: metadata.version,
author: metadata.author,
loaded: this.modules.has(name),
running: this.modules.has(name) ? this.modules.get(name).isRunning : false
});
}
return modules;
}
/**
* Register a custom module programmatically
*/
registerModule(name, ModuleClass, metadata = {}) {
this.availableModules.set(name, {
name,
class: ModuleClass,
description: metadata.description || `${name} module`,
version: metadata.version || '1.0.0',
author: metadata.author || 'Unknown',
custom: true
});
console.log(`Registered custom module: ${name}`);
}
async loadModule(moduleName, config) {
try {
// Check if module is available
if (!this.availableModules.has(moduleName)) {
throw new Error(`Module ${moduleName} not found`);
}
const metadata = this.availableModules.get(moduleName);
const ModuleClass = metadata.class;
const moduleInstance = new ModuleClass(config);
// Set up event listeners
moduleInstance.on('started', (data) => {
console.log(`[${moduleName.toUpperCase()}] Module started:`, data);
this.emit('moduleStarted', { module: moduleName, data });
});
moduleInstance.on('stopped', (data) => {
console.log(`[${moduleName.toUpperCase()}] Module stopped:`, data);
this.emit('moduleStopped', { module: moduleName, data });
});
moduleInstance.on('error', (error) => {
console.error(`[${moduleName.toUpperCase()}] Error:`, error.message);
this.emit('moduleError', { module: moduleName, error });
});
moduleInstance.on('log', (message) => {
console.log(`[${moduleName.toUpperCase()}] ${message}`);
});
this.modules.set(moduleName, moduleInstance);
console.log(`✓ Module loaded: ${moduleName} (v${metadata.version})`);
return moduleInstance;
} catch (error) {
console.error(`✗ Failed to load module ${moduleName}:`, error.message);
throw error;
}
}
async startModule(moduleName) {
const module = this.modules.get(moduleName);
if (!module) {
throw new Error(`Module ${moduleName} not loaded`);
}
await module.start();
}
async stopModule(moduleName) {
const module = this.modules.get(moduleName);
if (!module) {
throw new Error(`Module ${moduleName} not loaded`);
}
await module.stop();
}
async start() {
console.log('='.repeat(60));
console.log('OneStack - All-in-One Server');
console.log('='.repeat(60));
console.log('');
// Load configuration
console.log('Loading configuration...');
this.config = await this.configManager.load();
console.log('');
// Discover available modules
console.log('Discovering modules...');
await this.discoverModules();
console.log('');
// Start Admin Panel/API Server if enabled
if (this.config.server.adminPanel.enabled) {
console.log('Starting Admin Panel...');
await this.startAdminPanel();
console.log('');
}
// Load all enabled modules from configuration
console.log('Loading modules...');
for (const [moduleName, moduleConfig] of Object.entries(this.config.modules)) {
if (moduleConfig.enabled && this.availableModules.has(moduleName)) {
try {
await this.loadModule(moduleName, moduleConfig);
} catch (error) {
console.error(`Failed to load ${moduleName} module, skipping...`);
}
}
}
console.log('');
console.log('Starting modules...');
// Start all loaded modules
for (const [name, module] of this.modules) {
try {
await this.startModule(name);
} catch (error) {
console.error(`Failed to start ${name} module:`, error.message);
}
}
console.log('');
console.log('='.repeat(60));
console.log('All modules started successfully!');
if (this.config.server.adminPanel.enabled) {
console.log(`Admin Panel: http://localhost:${this.config.server.adminPanel.port}`);
}
console.log('Press Ctrl+C to stop the server');
console.log('='.repeat(60));
}
async startAdminPanel() {
const AdminPanelAPI = require('./admin-api');
this.apiServer = new AdminPanelAPI(this, this.configManager);
const host = this.config.server.adminPanel.host || '127.0.0.1';
const port = this.config.server.adminPanel.port;
await this.apiServer.start(port, host);
}
async stop() {
console.log('\nShutting down OneStack server...');
// Stop admin panel
if (this.apiServer) {
await this.apiServer.stop();
}
for (const [name, module] of this.modules) {
try {
await this.stopModule(name);
} catch (error) {
console.error(`Error stopping ${name} module:`, error.message);
}
}
console.log('Server stopped.');
process.exit(0);
}
getServerStatus() {
const moduleStatus = {};
for (const [name, module] of this.modules) {
moduleStatus[name] = module.getStatus();
}
return {
uptime: process.uptime(),
memory: process.memoryUsage(),
modules: moduleStatus,
config: this.config
};
}
async reloadModule(moduleName) {
if (!this.modules.has(moduleName)) {
throw new Error(`Module ${moduleName} not loaded`);
}
console.log(`Reloading module: ${moduleName}`);
await this.stopModule(moduleName);
const config = this.config.modules[moduleName];
await this.loadModule(moduleName, config);
await this.startModule(moduleName);
console.log(`Module ${moduleName} reloaded successfully`);
}
}
// Main execution
const server = new OneStackServer();
// Handle graceful shutdown
process.on('SIGINT', () => server.stop());
process.on('SIGTERM', () => server.stop());
// Handle uncaught errors
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
server.stop();
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
// Start the server
server.start().catch((error) => {
console.error('Failed to start server:', error);
process.exit(1);
});