Skip to content

Commit f39bb3b

Browse files
committed
Shutdown all PIO Home servers when can't start a new one
1 parent c84d7fa commit f39bb3b

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

src/home.js

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@
77
*/
88

99
import { getHomeDir, runPIOCommand } from './core';
10+
import { reportError, sleep } from './misc';
1011

1112
import SockJS from 'sockjs-client';
1213
import fs from 'fs-plus';
1314
import jsonrpc from 'jsonrpc-lite';
1415
import path from 'path';
1516
import qs from 'querystringify';
16-
import { reportError } from './misc';
1717
import request from 'request';
1818
import semver from 'semver';
1919
import tcpPortUsed from 'tcp-port-used';
@@ -22,6 +22,8 @@ import ws from 'ws';
2222

2323
const SERVER_LAUNCH_TIMEOUT = 5 * 60; // 5 minutes
2424
const HTTP_HOST = '127.0.0.1';
25+
const HTTP_PORT_BEGIN = 8010;
26+
const HTTP_PORT_END = 8100;
2527
let HTTP_PORT = 0;
2628
let IDECMDS_LISTENER_STATUS = 0;
2729

@@ -103,9 +105,9 @@ async function listenIDECommands(callback) {
103105
}
104106

105107
async function findFreePort() {
106-
let port = 8010;
108+
let port = HTTP_PORT_BEGIN;
107109
let inUse = false;
108-
while (port < 9000) {
110+
while (port < HTTP_PORT_END) {
109111
inUse = await new Promise(resolve => {
110112
tcpPortUsed.check(port, HTTP_HOST)
111113
.then(result => {
@@ -137,13 +139,21 @@ export async function ensureServerStarted(options={}) {
137139
const maxAttempts = 3;
138140
let attemptNums = 0;
139141
let lastError = undefined;
142+
let _port = 0;
140143
while (attemptNums < maxAttempts) {
141144
try {
142145
return await _ensureServerStarted(options);
143146
} catch (err) {
144147
lastError = err;
145148
console.warn(err);
146149
HTTP_PORT = 0;
150+
// stop all PIO Home servers
151+
_port = HTTP_PORT_BEGIN;
152+
while (_port < HTTP_PORT_END) {
153+
request.get(`http://${HTTP_HOST}:${_port}?__shutdown__=1`).on('error', () => {});
154+
_port++;
155+
}
156+
await sleep(2000); // wait for 2 secs while server stops
147157
}
148158
attemptNums++;
149159
}

src/misc.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ import tmp from 'tmp';
1818

1919
export const IS_WINDOWS = process.platform.startsWith('win');
2020

21+
export function sleep(ms) {
22+
return new Promise(resolve => setTimeout(resolve, ms));
23+
}
24+
2125
export function patchOSEnviron({ caller, useBuiltinPIOCore=true, extraPath, extraVars }) {
2226
process.env.PLATFORMIO_CALLER = caller;
2327
// Fix for platformio-atom-ide/issues/112

0 commit comments

Comments
 (0)