-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSmartPortResolver.js
More file actions
224 lines (186 loc) · 7.82 KB
/
Copy pathSmartPortResolver.js
File metadata and controls
224 lines (186 loc) · 7.82 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
const net = require('net');
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
/**
* Smart Port Resolver - Advanced port allocation with large random ranges
* Fixes restart loops caused by port conflicts between multiple servers
*/
class SmartPortResolver {
constructor(options = {}) {
// Use large port range as requested: 8000-9999 (2000 ports)
this.minPort = options.minPort || 8000;
this.maxPort = options.maxPort || 9999;
this.maxAttempts = options.maxAttempts || 50;
this.timeout = options.timeout || 3000; // 3 second timeout
// Track allocated ports to avoid immediate reuse
this.allocatedPorts = new Set();
this.lastCleanup = Date.now();
this.cleanupInterval = 60000; // Clean up after 1 minute
console.log(`[SmartPortResolver] Initialized with range ${this.minPort}-${this.maxPort} (${this.maxPort - this.minPort + 1} ports available)`);
}
/**
* Get a random port within the configured range
*/
getRandomPort() {
return Math.floor(Math.random() * (this.maxPort - this.minPort + 1)) + this.minPort;
}
/**
* Check if a port is available using multiple methods
*/
async isPortAvailable(port) {
// Method 1: Try JavaScript native approach first (fastest)
const isAvailableJS = await this.isPortAvailableJS(port);
if (!isAvailableJS) {
return false;
}
// Method 2: Use Unix utilities for additional verification
const isAvailableUnix = await this.isPortAvailableUnix(port);
return isAvailableUnix;
}
/**
* JavaScript-based port availability check
*/
async isPortAvailableJS(port) {
return new Promise((resolve) => {
const server = net.createServer();
const onError = () => {
resolve(false);
};
const onListening = () => {
server.close(() => {
resolve(true);
});
};
server.on('error', onError);
server.on('listening', onListening);
// Set timeout to prevent hanging
const timeout = setTimeout(() => {
server.removeAllListeners();
try {
server.close();
} catch (e) {
// Ignore close errors
}
resolve(false);
}, this.timeout);
server.listen(port, 'localhost', () => {
clearTimeout(timeout);
onListening();
});
});
}
/**
* Unix utilities-based port availability check
*/
async isPortAvailableUnix(port) {
try {
// Use netstat to check if port is in use
// -tuln: TCP and UDP, listening, numerical addresses
const { stdout } = await execAsync(`netstat -tuln 2>/dev/null | grep :${port} || true`, {
timeout: 2000
});
// If no output, port is available
const isInUse = stdout.trim().length > 0;
if (isInUse) {
// Double-check with lsof if available
try {
const { stdout: lsofOutput } = await execAsync(`lsof -i:${port} 2>/dev/null || true`, {
timeout: 1000
});
return lsofOutput.trim().length === 0;
} catch (e) {
// If lsof fails, trust netstat result
return false;
}
}
return true;
} catch (error) {
// If Unix utilities fail, fall back to JS-only check
console.log(`[SmartPortResolver] Unix check failed for port ${port}, using JS fallback: ${error.message}`);
return true; // Already verified by JS method
}
}
/**
* Find an available port using smart random allocation
*/
async findAvailablePort(botInstance = 'unknown') {
console.log(`[SmartPortResolver] Finding available port for ${botInstance}...`);
// Clean up old allocations periodically
this.cleanupAllocatedPorts();
const startTime = Date.now();
for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
const port = this.getRandomPort();
// Skip recently allocated ports to avoid immediate conflicts
if (this.allocatedPorts.has(port)) {
continue;
}
console.log(`[SmartPortResolver] ${botInstance} - Attempt ${attempt}/${this.maxAttempts}: Testing port ${port}`);
const isAvailable = await this.isPortAvailable(port);
if (isAvailable) {
// Mark port as allocated
this.allocatedPorts.add(port);
const duration = Date.now() - startTime;
console.log(`[SmartPortResolver] ✅ Found available port ${port} for ${botInstance} in ${duration}ms (attempt ${attempt})`);
return port;
} else {
console.log(`[SmartPortResolver] ❌ Port ${port} is occupied`);
}
}
const duration = Date.now() - startTime;
const errorMsg = `Unable to find available port for ${botInstance} after ${this.maxAttempts} attempts in ${duration}ms. Range: ${this.minPort}-${this.maxPort}`;
console.error(`[SmartPortResolver] ${errorMsg}`);
throw new Error(errorMsg);
}
/**
* Release a port allocation (call when server stops)
*/
releasePort(port, botInstance = 'unknown') {
if (this.allocatedPorts.has(port)) {
this.allocatedPorts.delete(port);
console.log(`[SmartPortResolver] Released port ${port} for ${botInstance}`);
}
}
/**
* Clean up old port allocations
*/
cleanupAllocatedPorts() {
const now = Date.now();
if (now - this.lastCleanup > this.cleanupInterval) {
const oldSize = this.allocatedPorts.size;
// Clear all allocations after cleanup interval
// This allows ports to be reused after servers have had time to start
this.allocatedPorts.clear();
this.lastCleanup = now;
if (oldSize > 0) {
console.log(`[SmartPortResolver] Cleaned up ${oldSize} old port allocations`);
}
}
}
/**
* Get statistics about port usage
*/
getStats() {
return {
portRange: `${this.minPort}-${this.maxPort}`,
totalPorts: this.maxPort - this.minPort + 1,
allocatedPorts: this.allocatedPorts.size,
availablePorts: (this.maxPort - this.minPort + 1) - this.allocatedPorts.size,
lastCleanup: new Date(this.lastCleanup).toISOString()
};
}
/**
* Test port availability with detailed diagnostics
*/
async testPort(port) {
console.log(`[SmartPortResolver] Testing port ${port} with detailed diagnostics...`);
const jsResult = await this.isPortAvailableJS(port);
console.log(`[SmartPortResolver] JavaScript check: ${jsResult ? 'AVAILABLE' : 'OCCUPIED'}`);
const unixResult = await this.isPortAvailableUnix(port);
console.log(`[SmartPortResolver] Unix utilities check: ${unixResult ? 'AVAILABLE' : 'OCCUPIED'}`);
const finalResult = jsResult && unixResult;
console.log(`[SmartPortResolver] Final result: ${finalResult ? 'AVAILABLE' : 'OCCUPIED'}`);
return finalResult;
}
}
module.exports = SmartPortResolver;