删除掉remote-container.ts中的一些调试信息
This commit is contained in:
@@ -15,7 +15,7 @@ import DevstarAPIHandler from './devstar-api';
|
|||||||
export default class RemoteContainer {
|
export default class RemoteContainer {
|
||||||
private user: User;
|
private user: User;
|
||||||
private sshProcesses?: Map<string, any>;
|
private sshProcesses?: Map<string, any>;
|
||||||
private portMappings: Map<string, Array<{containerPort: number, localPort: number, label: string, source: string}>> = new Map();
|
private portMappings: Map<string, Array<{ containerPort: number, localPort: number, label: string, source: string }>> = new Map();
|
||||||
private statusBarItems?: Map<string, vscode.StatusBarItem>;
|
private statusBarItems?: Map<string, vscode.StatusBarItem>;
|
||||||
|
|
||||||
constructor(user: User) {
|
constructor(user: User) {
|
||||||
@@ -30,12 +30,7 @@ export default class RemoteContainer {
|
|||||||
* 第一次打开远程项目
|
* 第一次打开远程项目
|
||||||
*/
|
*/
|
||||||
async firstOpenProject(host: string, hostname: string, port: number, username: string, path: string, context: vscode.ExtensionContext) {
|
async firstOpenProject(host: string, hostname: string, port: number, username: string, path: string, context: vscode.ExtensionContext) {
|
||||||
console.log(`[RemoteContainer] firstOpenProject called with:`, { host, hostname, port, username, path });
|
|
||||||
|
|
||||||
if (vscode.env.remoteName) {
|
if (vscode.env.remoteName) {
|
||||||
// 远程环境
|
|
||||||
console.log(`[RemoteContainer] Running in remote environment: ${vscode.env.remoteName}`);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await vscode.commands.executeCommand('workbench.action.terminal.newLocal');
|
await vscode.commands.executeCommand('workbench.action.terminal.newLocal');
|
||||||
const terminal = vscode.window.terminals[vscode.window.terminals.length - 1];
|
const terminal = vscode.window.terminals[vscode.window.terminals.length - 1];
|
||||||
@@ -69,38 +64,30 @@ export default class RemoteContainer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`[RemoteContainer] Sending command to terminal: ${command}`);
|
|
||||||
terminal.sendText(command);
|
terminal.sendText(command);
|
||||||
} else {
|
} else {
|
||||||
console.error(`[RemoteContainer] Failed to create or access terminal`);
|
|
||||||
vscode.window.showErrorMessage('无法创建终端,请检查终端是否可用。');
|
vscode.window.showErrorMessage('无法创建终端,请检查终端是否可用。');
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
console.error(`[RemoteContainer] Error in remote environment:`, error);
|
|
||||||
vscode.window.showErrorMessage(`远程环境操作失败: ${errorMessage}`);
|
vscode.window.showErrorMessage(`远程环境操作失败: ${errorMessage}`);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
console.log(`[RemoteContainer] Running in local environment, attempting firstConnect`);
|
|
||||||
try {
|
try {
|
||||||
await this.firstConnect(host, hostname, username, port, path)
|
await this.firstConnect(host, hostname, username, port, path)
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
if (res === 'success') {
|
if (res === 'success') {
|
||||||
console.log(`[RemoteContainer] firstConnect succeeded, opening remote folder`);
|
|
||||||
this.openRemoteFolder(host, port, username, path);
|
this.openRemoteFolder(host, port, username, path);
|
||||||
} else {
|
} else {
|
||||||
console.error(`[RemoteContainer] firstConnect returned: ${res}`);
|
|
||||||
vscode.window.showErrorMessage('首次连接容器失败,请检查网络和容器状态。');
|
vscode.window.showErrorMessage('首次连接容器失败,请检查网络和容器状态。');
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
console.error(`[RemoteContainer] firstConnect failed:`, error);
|
|
||||||
vscode.window.showErrorMessage(`首次连接容器时发生错误: ${errorMessage}`);
|
vscode.window.showErrorMessage(`首次连接容器时发生错误: ${errorMessage}`);
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
console.error(`[RemoteContainer] Error in local environment firstOpenProject:`, error);
|
|
||||||
vscode.window.showErrorMessage(`打开项目失败: ${errorMessage}`);
|
vscode.window.showErrorMessage(`打开项目失败: ${errorMessage}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -110,8 +97,6 @@ export default class RemoteContainer {
|
|||||||
* local environment,第一次连接其他项目
|
* local environment,第一次连接其他项目
|
||||||
*/
|
*/
|
||||||
async firstConnect(host: string, hostname: string, username: string, port: number, projectPath?: string): Promise<string> {
|
async firstConnect(host: string, hostname: string, username: string, port: number, projectPath?: string): Promise<string> {
|
||||||
console.log(`[RemoteContainer] firstConnect called with:`, { host, hostname, username, port, projectPath });
|
|
||||||
|
|
||||||
return new Promise(async (resolve, reject) => {
|
return new Promise(async (resolve, reject) => {
|
||||||
const ssh = new NodeSSH();
|
const ssh = new NodeSSH();
|
||||||
|
|
||||||
@@ -121,32 +106,21 @@ export default class RemoteContainer {
|
|||||||
cancellable: false
|
cancellable: false
|
||||||
}, async (progress) => {
|
}, async (progress) => {
|
||||||
try {
|
try {
|
||||||
console.log(`[RemoteContainer] Checking SSH keys existence`);
|
|
||||||
|
|
||||||
if (!this.user.existUserPrivateKey() || !this.user.existUserPublicKey()) {
|
if (!this.user.existUserPrivateKey() || !this.user.existUserPublicKey()) {
|
||||||
console.log(`[RemoteContainer] SSH keys not found, creating new keys`);
|
|
||||||
await this.user.createUserSSHKey();
|
await this.user.createUserSSHKey();
|
||||||
|
|
||||||
console.log(`[RemoteContainer] Uploading public key`);
|
|
||||||
const devstarAPIHandler = new DevstarAPIHandler();
|
const devstarAPIHandler = new DevstarAPIHandler();
|
||||||
const uploadResult = await devstarAPIHandler.uploadUserPublicKey(this.user);
|
const uploadResult = await devstarAPIHandler.uploadUserPublicKey(this.user);
|
||||||
if (uploadResult !== "ok") {
|
if (uploadResult !== "ok") {
|
||||||
throw new Error('Upload public key failed.');
|
throw new Error('Upload public key failed.');
|
||||||
}
|
}
|
||||||
console.log(`[RemoteContainer] Public key uploaded successfully`);
|
|
||||||
} else {
|
|
||||||
console.log(`[RemoteContainer] SSH keys already exist`);
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
|
||||||
console.error("[RemoteContainer] Failed to first connect container - SSH key setup: ", error);
|
|
||||||
reject(error);
|
reject(error);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log(`[RemoteContainer] Attempting SSH connection to ${hostname}:${port} as ${username}`);
|
|
||||||
|
|
||||||
await ssh.connect({
|
await ssh.connect({
|
||||||
host: hostname,
|
host: hostname,
|
||||||
username: 'root',
|
username: 'root',
|
||||||
@@ -160,19 +134,15 @@ export default class RemoteContainer {
|
|||||||
_prompts: any[],
|
_prompts: any[],
|
||||||
finish: (responses: string[]) => void
|
finish: (responses: string[]) => void
|
||||||
) => {
|
) => {
|
||||||
console.log(`[RemoteContainer] Keyboard interactive authentication required`);
|
|
||||||
finish([]);
|
finish([]);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`[RemoteContainer] SSH connection established successfully`);
|
|
||||||
progress.report({ message: vscode.l10n.t("Connected! Start installation") });
|
progress.report({ message: vscode.l10n.t("Connected! Start installation") });
|
||||||
|
|
||||||
console.log(`[RemoteContainer] Getting VSCode commit ID`);
|
|
||||||
const vscodeCommitId = await utils.getVsCodeCommitId();
|
const vscodeCommitId = await utils.getVsCodeCommitId();
|
||||||
|
|
||||||
if ("" !== vscodeCommitId) {
|
if ("" !== vscodeCommitId) {
|
||||||
console.log(`[RemoteContainer] VSCode commit ID: ${vscodeCommitId}`);
|
|
||||||
const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz`;
|
const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz`;
|
||||||
const installVscodeServerScript = `
|
const installVscodeServerScript = `
|
||||||
mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\
|
mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\
|
||||||
@@ -190,47 +160,29 @@ export default class RemoteContainer {
|
|||||||
fi
|
fi
|
||||||
`;
|
`;
|
||||||
|
|
||||||
console.log(`[RemoteContainer] Executing installation script`);
|
|
||||||
const installResult = await ssh.execCommand(installVscodeServerScript);
|
const installResult = await ssh.execCommand(installVscodeServerScript);
|
||||||
|
|
||||||
if (installResult.code === 0) {
|
if (installResult.code === 0) {
|
||||||
console.log("[RemoteContainer] VSCode server and extension installed successfully");
|
|
||||||
console.log("[RemoteContainer] Installation stdout:", installResult.stdout);
|
|
||||||
if (installResult.stderr) {
|
|
||||||
console.warn("[RemoteContainer] Installation stderr:", installResult.stderr);
|
|
||||||
}
|
|
||||||
|
|
||||||
vscode.window.showInformationMessage(vscode.l10n.t('Installation completed!'));
|
vscode.window.showInformationMessage(vscode.l10n.t('Installation completed!'));
|
||||||
} else {
|
} else {
|
||||||
console.error("[RemoteContainer] Installation failed with code:", installResult.code);
|
|
||||||
console.error("[RemoteContainer] Installation stderr:", installResult.stderr);
|
|
||||||
throw new Error(`Installation failed with exit code ${installResult.code}: ${installResult.stderr}`);
|
throw new Error(`Installation failed with exit code ${installResult.code}: ${installResult.stderr}`);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Failed to get VSCode commit ID');
|
throw new Error('Failed to get VSCode commit ID');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 移除端口映射设置,移到 openRemoteFolder 中
|
|
||||||
// 只记录项目路径信息,供后续使用
|
|
||||||
if (projectPath) {
|
if (projectPath) {
|
||||||
console.log(`[RemoteContainer] Project path recorded for port forwarding: ${projectPath}`);
|
|
||||||
// 这里可以存储项目路径信息,但不在第一次连接时建立端口映射
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await ssh.dispose();
|
await ssh.dispose();
|
||||||
console.log(`[RemoteContainer] SSH connection disposed`);
|
|
||||||
|
|
||||||
console.log(`[RemoteContainer] Storing project SSH info`);
|
|
||||||
await this.storeProjectSSHInfo(host, hostname, port, 'root');
|
await this.storeProjectSSHInfo(host, hostname, port, 'root');
|
||||||
|
|
||||||
resolve('success');
|
resolve('success');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
|
||||||
console.error('[RemoteContainer] Failed to install vscode-server and extension: ', error);
|
|
||||||
try {
|
try {
|
||||||
await ssh.dispose();
|
await ssh.dispose();
|
||||||
} catch (disposeError) {
|
} catch (disposeError) {
|
||||||
console.error('[RemoteContainer] Error disposing SSH connection: ', disposeError);
|
|
||||||
}
|
}
|
||||||
reject(error);
|
reject(error);
|
||||||
}
|
}
|
||||||
@@ -247,18 +199,14 @@ export default class RemoteContainer {
|
|||||||
otherPortsAttributes?: any;
|
otherPortsAttributes?: any;
|
||||||
}> {
|
}> {
|
||||||
try {
|
try {
|
||||||
console.log(`[RemoteContainer] Looking for devcontainer.json at: ${containerPath}`);
|
|
||||||
|
|
||||||
const findResult = await ssh.execCommand(`find ${containerPath} -name "devcontainer.json" -type f`);
|
const findResult = await ssh.execCommand(`find ${containerPath} -name "devcontainer.json" -type f`);
|
||||||
|
|
||||||
if (findResult.code === 0 && findResult.stdout.trim()) {
|
if (findResult.code === 0 && findResult.stdout.trim()) {
|
||||||
const devcontainerPath = findResult.stdout.trim().split('\n')[0];
|
const devcontainerPath = findResult.stdout.trim().split('\n')[0];
|
||||||
console.log(`[RemoteContainer] Found devcontainer.json at: ${devcontainerPath}`);
|
|
||||||
|
|
||||||
const readResult = await ssh.execCommand(`cat ${devcontainerPath}`);
|
const readResult = await ssh.execCommand(`cat ${devcontainerPath}`);
|
||||||
if (readResult.code === 0) {
|
if (readResult.code === 0) {
|
||||||
const devcontainerConfig = JSON.parse(readResult.stdout);
|
const devcontainerConfig = JSON.parse(readResult.stdout);
|
||||||
console.log(`[RemoteContainer] Parsed devcontainer.json:`, devcontainerConfig);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
portsAttributes: devcontainerConfig.portsAttributes || {},
|
portsAttributes: devcontainerConfig.portsAttributes || {},
|
||||||
@@ -266,11 +214,8 @@ export default class RemoteContainer {
|
|||||||
otherPortsAttributes: devcontainerConfig.otherPortsAttributes
|
otherPortsAttributes: devcontainerConfig.otherPortsAttributes
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
console.log(`[RemoteContainer] No devcontainer.json found in ${containerPath}`);
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[RemoteContainer] Error reading devcontainer.json:`, error);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { portsAttributes: {} };
|
return { portsAttributes: {} };
|
||||||
@@ -280,34 +225,22 @@ export default class RemoteContainer {
|
|||||||
* 查找可用的本地端口 - 优先使用相同端口
|
* 查找可用的本地端口 - 优先使用相同端口
|
||||||
*/
|
*/
|
||||||
private async findAvailableLocalPort(containerPort: number): Promise<number> {
|
private async findAvailableLocalPort(containerPort: number): Promise<number> {
|
||||||
// 首先尝试使用相同的端口号
|
|
||||||
if (await this.isPortAvailable(containerPort)) {
|
if (await this.isPortAvailable(containerPort)) {
|
||||||
console.log(`[RemoteContainer] Using same port: ${containerPort}`);
|
|
||||||
return containerPort;
|
return containerPort;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果相同端口被占用,尝试在附近查找可用端口
|
|
||||||
console.log(`[RemoteContainer] Port ${containerPort} is occupied, finding alternative...`);
|
|
||||||
|
|
||||||
// 在 containerPort ± 10 范围内查找
|
|
||||||
for (let offset = 1; offset <= 10; offset++) {
|
for (let offset = 1; offset <= 10; offset++) {
|
||||||
// 尝试 containerPort + offset
|
|
||||||
const port1 = containerPort + offset;
|
const port1 = containerPort + offset;
|
||||||
if (port1 < 65536 && await this.isPortAvailable(port1)) {
|
if (port1 < 65536 && await this.isPortAvailable(port1)) {
|
||||||
console.log(`[RemoteContainer] Using alternative port: ${port1}`);
|
|
||||||
return port1;
|
return port1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 尝试 containerPort - offset
|
|
||||||
const port2 = containerPort - offset;
|
const port2 = containerPort - offset;
|
||||||
if (port2 > 0 && await this.isPortAvailable(port2)) {
|
if (port2 > 0 && await this.isPortAvailable(port2)) {
|
||||||
console.log(`[RemoteContainer] Using alternative port: ${port2}`);
|
|
||||||
return port2;
|
return port2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果附近端口都被占用,使用随机端口
|
|
||||||
console.log(`[RemoteContainer] No nearby ports available, using random port`);
|
|
||||||
return this.findRandomAvailablePort();
|
return this.findRandomAvailablePort();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,8 +283,6 @@ export default class RemoteContainer {
|
|||||||
* 建立端口映射 - 根据 devcontainer.json 配置
|
* 建立端口映射 - 根据 devcontainer.json 配置
|
||||||
*/
|
*/
|
||||||
private async setupPortForwarding(hostname: string, port: number, containerPath: string): Promise<void> {
|
private async setupPortForwarding(hostname: string, port: number, containerPath: string): Promise<void> {
|
||||||
console.log(`[RemoteContainer] Setting up port forwarding for ${hostname}:${port}`);
|
|
||||||
|
|
||||||
const ssh = new NodeSSH();
|
const ssh = new NodeSSH();
|
||||||
const portMappings: Array<{ containerPort: number, localPort: number, label: string, source: string }> = [];
|
const portMappings: Array<{ containerPort: number, localPort: number, label: string, source: string }> = [];
|
||||||
|
|
||||||
@@ -364,11 +295,8 @@ export default class RemoteContainer {
|
|||||||
readyTimeout: 30000,
|
readyTimeout: 30000,
|
||||||
});
|
});
|
||||||
|
|
||||||
// 获取完整的端口配置
|
|
||||||
const portsConfig = await this.getPortsConfigFromDevContainer(ssh, containerPath);
|
const portsConfig = await this.getPortsConfigFromDevContainer(ssh, containerPath);
|
||||||
console.log(`[RemoteContainer] Ports config found:`, portsConfig);
|
|
||||||
|
|
||||||
// 1. 首先处理 forwardPorts(显式指定的端口)
|
|
||||||
if (portsConfig.forwardPorts && portsConfig.forwardPorts.length > 0) {
|
if (portsConfig.forwardPorts && portsConfig.forwardPorts.length > 0) {
|
||||||
for (const containerPort of portsConfig.forwardPorts) {
|
for (const containerPort of portsConfig.forwardPorts) {
|
||||||
const localPort = await this.findAvailableLocalPort(containerPort);
|
const localPort = await this.findAvailableLocalPort(containerPort);
|
||||||
@@ -380,16 +308,12 @@ export default class RemoteContainer {
|
|||||||
label: `Port ${containerPort}`,
|
label: `Port ${containerPort}`,
|
||||||
source: 'forwardPorts'
|
source: 'forwardPorts'
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`[RemoteContainer] ForwardPorts mapping: localhost:${localPort} -> container:${containerPort}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 处理 portsAttributes 配置的端口
|
|
||||||
for (const [containerPortStr, attributes] of Object.entries(portsConfig.portsAttributes)) {
|
for (const [containerPortStr, attributes] of Object.entries(portsConfig.portsAttributes)) {
|
||||||
const containerPort = parseInt(containerPortStr);
|
const containerPort = parseInt(containerPortStr);
|
||||||
if (!isNaN(containerPort)) {
|
if (!isNaN(containerPort)) {
|
||||||
// 检查是否已经在 forwardPorts 中处理过
|
|
||||||
const alreadyMapped = portMappings.some(m => m.containerPort === containerPort);
|
const alreadyMapped = portMappings.some(m => m.containerPort === containerPort);
|
||||||
if (!alreadyMapped) {
|
if (!alreadyMapped) {
|
||||||
const localPort = await this.findAvailableLocalPort(containerPort);
|
const localPort = await this.findAvailableLocalPort(containerPort);
|
||||||
@@ -402,28 +326,22 @@ export default class RemoteContainer {
|
|||||||
label,
|
label,
|
||||||
source: 'portsAttributes'
|
source: 'portsAttributes'
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`[RemoteContainer] PortsAttributes mapping: localhost:${localPort} -> container:${containerPort}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await ssh.dispose();
|
await ssh.dispose();
|
||||||
|
|
||||||
// 存储端口映射信息
|
|
||||||
const mappingKey = `${hostname}:${port}`;
|
const mappingKey = `${hostname}:${port}`;
|
||||||
this.portMappings.set(mappingKey, portMappings);
|
this.portMappings.set(mappingKey, portMappings);
|
||||||
|
|
||||||
// 显示映射汇总信息
|
|
||||||
if (portMappings.length > 0) {
|
if (portMappings.length > 0) {
|
||||||
this.showPortMappingsSummary(portMappings);
|
this.showPortMappingsSummary(portMappings);
|
||||||
|
|
||||||
// 注册命令以便后续查看
|
|
||||||
this.registerPortMappingsCommands(mappingKey, portMappings);
|
this.registerPortMappingsCommands(mappingKey, portMappings);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[RemoteContainer] Error setting up port forwarding:`, error);
|
|
||||||
await ssh.dispose();
|
await ssh.dispose();
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -448,19 +366,15 @@ export default class RemoteContainer {
|
|||||||
const sshProcess = spawn('ssh', sshArgs);
|
const sshProcess = spawn('ssh', sshArgs);
|
||||||
|
|
||||||
sshProcess.on('error', (error: Error) => {
|
sshProcess.on('error', (error: Error) => {
|
||||||
console.error(`[RemoteContainer] SSH port forward error:`, error);
|
|
||||||
reject(error);
|
reject(error);
|
||||||
});
|
});
|
||||||
|
|
||||||
sshProcess.stdout.on('data', (data: Buffer) => {
|
sshProcess.stdout.on('data', (data: Buffer) => {
|
||||||
console.log(`[RemoteContainer] SSH stdout:`, data.toString());
|
|
||||||
});
|
});
|
||||||
|
|
||||||
sshProcess.stderr.on('data', (data: Buffer) => {
|
sshProcess.stderr.on('data', (data: Buffer) => {
|
||||||
console.log(`[RemoteContainer] SSH stderr:`, data.toString());
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 存储进程引用以便后续管理
|
|
||||||
if (!this.sshProcesses) {
|
if (!this.sshProcesses) {
|
||||||
this.sshProcesses = new Map();
|
this.sshProcesses = new Map();
|
||||||
}
|
}
|
||||||
@@ -468,7 +382,6 @@ export default class RemoteContainer {
|
|||||||
this.sshProcesses.set(key, sshProcess);
|
this.sshProcesses.set(key, sshProcess);
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
console.log(`[RemoteContainer] SSH port forward established: ${localPort} -> ${hostname}:${containerPort}`);
|
|
||||||
resolve();
|
resolve();
|
||||||
}, 2000);
|
}, 2000);
|
||||||
});
|
});
|
||||||
@@ -497,7 +410,6 @@ export default class RemoteContainer {
|
|||||||
vscode.env.clipboard.writeText(copyText);
|
vscode.env.clipboard.writeText(copyText);
|
||||||
vscode.window.showInformationMessage('端口映射信息已复制到剪贴板');
|
vscode.window.showInformationMessage('端口映射信息已复制到剪贴板');
|
||||||
} else if (selection === '在浏览器中打开' && portMappings.length > 0) {
|
} else if (selection === '在浏览器中打开' && portMappings.length > 0) {
|
||||||
// 打开第一个映射的地址
|
|
||||||
vscode.env.openExternal(vscode.Uri.parse(`http://localhost:${portMappings[0].localPort}`));
|
vscode.env.openExternal(vscode.Uri.parse(`http://localhost:${portMappings[0].localPort}`));
|
||||||
} else if (selection === '查看详细信息') {
|
} else if (selection === '查看详细信息') {
|
||||||
this.showPortMappingsInOutputChannel('current', 0);
|
this.showPortMappingsInOutputChannel('current', 0);
|
||||||
@@ -508,36 +420,31 @@ export default class RemoteContainer {
|
|||||||
/**
|
/**
|
||||||
* 注册端口映射查看命令
|
* 注册端口映射查看命令
|
||||||
*/
|
*/
|
||||||
private registerPortMappingsCommands(mappingKey: string, portMappings: Array<{containerPort: number, localPort: number, label: string, source: string}>): void {
|
private registerPortMappingsCommands(mappingKey: string, portMappings: Array<{ containerPort: number, localPort: number, label: string, source: string }>): void {
|
||||||
// 注册一个全局命令来显示端口映射信息
|
|
||||||
const showPortMappingsCommand = `devstar.showPortMappings.${mappingKey.replace(/[^a-zA-Z0-9]/g, '_')}`;
|
const showPortMappingsCommand = `devstar.showPortMappings.${mappingKey.replace(/[^a-zA-Z0-9]/g, '_')}`;
|
||||||
|
|
||||||
vscode.commands.registerCommand(showPortMappingsCommand, () => {
|
vscode.commands.registerCommand(showPortMappingsCommand, () => {
|
||||||
this.showPortMappingsSummary(portMappings);
|
this.showPortMappingsSummary(portMappings);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 在状态栏显示端口映射信息
|
|
||||||
this.createStatusBarItem(mappingKey, portMappings);
|
this.createStatusBarItem(mappingKey, portMappings);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建状态栏项目
|
* 创建状态栏项目
|
||||||
*/
|
*/
|
||||||
private createStatusBarItem(mappingKey: string, portMappings: Array<{containerPort: number, localPort: number, label: string, source: string}>): void {
|
private createStatusBarItem(mappingKey: string, portMappings: Array<{ containerPort: number, localPort: number, label: string, source: string }>): void {
|
||||||
if (portMappings.length === 0) return;
|
if (portMappings.length === 0) return;
|
||||||
|
|
||||||
const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
|
const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
|
||||||
|
|
||||||
// 显示端口数量
|
|
||||||
statusBarItem.text = `$(plug) ${portMappings.length} Ports`;
|
statusBarItem.text = `$(plug) ${portMappings.length} Ports`;
|
||||||
statusBarItem.tooltip = `点击查看 ${portMappings.length} 个端口映射详情`;
|
statusBarItem.tooltip = `点击查看 ${portMappings.length} 个端口映射详情`;
|
||||||
|
|
||||||
// 添加命令
|
|
||||||
statusBarItem.command = `devstar.showPortMappings.${mappingKey.replace(/[^a-zA-Z0-9]/g, '_')}`;
|
statusBarItem.command = `devstar.showPortMappings.${mappingKey.replace(/[^a-zA-Z0-9]/g, '_')}`;
|
||||||
|
|
||||||
statusBarItem.show();
|
statusBarItem.show();
|
||||||
|
|
||||||
// 存储状态栏项目以便后续清理
|
|
||||||
if (!this.statusBarItems) {
|
if (!this.statusBarItems) {
|
||||||
this.statusBarItems = new Map();
|
this.statusBarItems = new Map();
|
||||||
}
|
}
|
||||||
@@ -547,7 +454,7 @@ export default class RemoteContainer {
|
|||||||
/**
|
/**
|
||||||
* 获取当前活动的端口映射信息
|
* 获取当前活动的端口映射信息
|
||||||
*/
|
*/
|
||||||
public getActivePortMappings(hostname: string, port: number): Array<{containerPort: number, localPort: number, label: string, source: string}> {
|
public getActivePortMappings(hostname: string, port: number): Array<{ containerPort: number, localPort: number, label: string, source: string }> {
|
||||||
const mappingKey = `${hostname}:${port}`;
|
const mappingKey = `${hostname}:${port}`;
|
||||||
return this.portMappings.get(mappingKey) || [];
|
return this.portMappings.get(mappingKey) || [];
|
||||||
}
|
}
|
||||||
@@ -577,10 +484,10 @@ export default class RemoteContainer {
|
|||||||
|
|
||||||
const outputChannel = vscode.window.createOutputChannel('DevStar Port Mappings');
|
const outputChannel = vscode.window.createOutputChannel('DevStar Port Mappings');
|
||||||
outputChannel.show();
|
outputChannel.show();
|
||||||
|
|
||||||
outputChannel.appendLine(`🎯 端口映射信息 - ${hostname}:${port}`);
|
outputChannel.appendLine(`🎯 端口映射信息 - ${hostname}:${port}`);
|
||||||
outputChannel.appendLine('='.repeat(50));
|
outputChannel.appendLine('='.repeat(50));
|
||||||
|
|
||||||
mappings.forEach((mapping, index) => {
|
mappings.forEach((mapping, index) => {
|
||||||
outputChannel.appendLine(`${index + 1}. ${mapping.label}`);
|
outputChannel.appendLine(`${index + 1}. ${mapping.label}`);
|
||||||
outputChannel.appendLine(` 容器端口: ${mapping.containerPort}`);
|
outputChannel.appendLine(` 容器端口: ${mapping.containerPort}`);
|
||||||
@@ -589,7 +496,7 @@ export default class RemoteContainer {
|
|||||||
outputChannel.appendLine(` 配置来源: ${mapping.source}`);
|
outputChannel.appendLine(` 配置来源: ${mapping.source}`);
|
||||||
outputChannel.appendLine('');
|
outputChannel.appendLine('');
|
||||||
});
|
});
|
||||||
|
|
||||||
outputChannel.appendLine('💡 提示: 您可以在浏览器中访问上述本地端口来访问容器中的服务');
|
outputChannel.appendLine('💡 提示: 您可以在浏览器中访问上述本地端口来访问容器中的服务');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -597,40 +504,29 @@ export default class RemoteContainer {
|
|||||||
* 本地环境,保存项目的ssh连接信息
|
* 本地环境,保存项目的ssh连接信息
|
||||||
*/
|
*/
|
||||||
async storeProjectSSHInfo(host: string, hostname: string, port: number, username: string): Promise<void> {
|
async storeProjectSSHInfo(host: string, hostname: string, port: number, username: string): Promise<void> {
|
||||||
console.log(`[RemoteContainer] storeProjectSSHInfo called with:`, { host, hostname, port, username });
|
|
||||||
|
|
||||||
const sshConfigPath = path.join(os.homedir(), '.ssh', 'config');
|
const sshConfigPath = path.join(os.homedir(), '.ssh', 'config');
|
||||||
console.log(`[RemoteContainer] SSH config path: ${sshConfigPath}`);
|
|
||||||
|
|
||||||
let canAppendSSHConfig = true;
|
let canAppendSSHConfig = true;
|
||||||
if (fs.existsSync(sshConfigPath)) {
|
if (fs.existsSync(sshConfigPath)) {
|
||||||
console.log(`[RemoteContainer] SSH config file exists, checking for existing host`);
|
|
||||||
|
|
||||||
const reader = rd.createInterface(fs.createReadStream(sshConfigPath));
|
const reader = rd.createInterface(fs.createReadStream(sshConfigPath));
|
||||||
|
|
||||||
for await (const line of reader) {
|
for await (const line of reader) {
|
||||||
if (line.includes(`Host ${host}`)) {
|
if (line.includes(`Host ${host}`)) {
|
||||||
console.log(`[RemoteContainer] Host ${host} already exists in SSH config`);
|
|
||||||
canAppendSSHConfig = false;
|
canAppendSSHConfig = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
console.log(`[RemoteContainer] SSH config file does not exist, will create it`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (canAppendSSHConfig) {
|
if (canAppendSSHConfig) {
|
||||||
const privateKeyPath = this.user.getUserPrivateKeyPath();
|
const privateKeyPath = this.user.getUserPrivateKeyPath();
|
||||||
console.log(`[RemoteContainer] Using private key path: ${privateKeyPath}`);
|
|
||||||
|
|
||||||
const newSShConfigContent =
|
const newSShConfigContent =
|
||||||
`\nHost ${host}\n HostName ${hostname}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ${privateKeyPath}\n `;
|
`\nHost ${host}\n HostName ${hostname}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ${privateKeyPath}\n `;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
fs.writeFileSync(sshConfigPath, newSShConfigContent, { encoding: 'utf8', flag: 'a' });
|
fs.writeFileSync(sshConfigPath, newSShConfigContent, { encoding: 'utf8', flag: 'a' });
|
||||||
console.log('[RemoteContainer] Host registered in local ssh config');
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[RemoteContainer] Failed to write SSH config:', error);
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -640,40 +536,30 @@ export default class RemoteContainer {
|
|||||||
* local env
|
* local env
|
||||||
*/
|
*/
|
||||||
async openRemoteFolder(host: string, port: number, username: string, path: string): Promise<void> {
|
async openRemoteFolder(host: string, port: number, username: string, path: string): Promise<void> {
|
||||||
console.log(`[RemoteContainer] openRemoteFolder called with:`, { host, port, username, path });
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 先设置端口映射(保留这里的端口映射建立)
|
|
||||||
const sshConfig = await this.getSSHConfig(host);
|
const sshConfig = await this.getSSHConfig(host);
|
||||||
if (sshConfig) {
|
if (sshConfig) {
|
||||||
try {
|
try {
|
||||||
await this.setupPortForwarding(sshConfig.hostname, port, path);
|
await this.setupPortForwarding(sshConfig.hostname, port, path);
|
||||||
console.log(`[RemoteContainer] Port forwarding established for existing connection`);
|
|
||||||
|
|
||||||
// 延迟显示端口映射信息,确保用户能看到
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.showPortMappingsPanel(sshConfig.hostname, port);
|
this.showPortMappingsPanel(sshConfig.hostname, port);
|
||||||
}, 3000);
|
}, 3000);
|
||||||
|
|
||||||
} catch (portError) {
|
} catch (portError) {
|
||||||
console.warn(`[RemoteContainer] Port forwarding setup failed:`, portError);
|
|
||||||
vscode.window.showWarningMessage('端口映射设置失败,但容器连接已建立');
|
vscode.window.showWarningMessage('端口映射设置失败,但容器连接已建立');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 然后打开远程文件夹
|
|
||||||
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
|
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
|
||||||
terminal.show(true);
|
terminal.show(true);
|
||||||
|
|
||||||
const command = `code --remote ssh-remote+root@${host}:${port} ${path} --reuse-window`;
|
const command = `code --remote ssh-remote+root@${host}:${port} ${path} --reuse-window`;
|
||||||
console.log(`[RemoteContainer] Sending command to terminal: ${command}`);
|
|
||||||
|
|
||||||
terminal.sendText(command);
|
terminal.sendText(command);
|
||||||
console.log(`[RemoteContainer] Command sent successfully`);
|
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
console.error(`[RemoteContainer] Error in openRemoteFolder:`, error);
|
|
||||||
vscode.window.showErrorMessage(`打开远程文件夹失败: ${errorMessage}`);
|
vscode.window.showErrorMessage(`打开远程文件夹失败: ${errorMessage}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -720,22 +606,16 @@ export default class RemoteContainer {
|
|||||||
* 清理端口映射和相关UI
|
* 清理端口映射和相关UI
|
||||||
*/
|
*/
|
||||||
public cleanupPortForwarding(hostname?: string, port?: number): void {
|
public cleanupPortForwarding(hostname?: string, port?: number): void {
|
||||||
// 清理SSH进程
|
|
||||||
if (this.sshProcesses) {
|
if (this.sshProcesses) {
|
||||||
console.log(`[RemoteContainer] Cleaning up ${this.sshProcesses.size} SSH port forwarding processes`);
|
|
||||||
|
|
||||||
for (const [key, process] of this.sshProcesses.entries()) {
|
for (const [key, process] of this.sshProcesses.entries()) {
|
||||||
try {
|
try {
|
||||||
process.kill();
|
process.kill();
|
||||||
console.log(`[RemoteContainer] Killed SSH process: ${key}`);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`[RemoteContainer] Failed to kill process ${key}:`, error);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.sshProcesses.clear();
|
this.sshProcesses.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 清理状态栏项目
|
|
||||||
if (this.statusBarItems) {
|
if (this.statusBarItems) {
|
||||||
if (hostname && port) {
|
if (hostname && port) {
|
||||||
const mappingKey = `${hostname}:${port}`;
|
const mappingKey = `${hostname}:${port}`;
|
||||||
@@ -745,15 +625,13 @@ export default class RemoteContainer {
|
|||||||
this.statusBarItems.delete(mappingKey);
|
this.statusBarItems.delete(mappingKey);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 清理所有状态栏项目
|
|
||||||
for (const [_, statusBarItem] of this.statusBarItems) {
|
for (const [_, statusBarItem] of this.statusBarItems) {
|
||||||
statusBarItem.dispose();
|
statusBarItem.dispose();
|
||||||
}
|
}
|
||||||
this.statusBarItems.clear();
|
this.statusBarItems.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 清理端口映射信息
|
|
||||||
if (hostname && port) {
|
if (hostname && port) {
|
||||||
const mappingKey = `${hostname}:${port}`;
|
const mappingKey = `${hostname}:${port}`;
|
||||||
this.portMappings.delete(mappingKey);
|
this.portMappings.delete(mappingKey);
|
||||||
@@ -767,19 +645,14 @@ export default class RemoteContainer {
|
|||||||
* 打开项目(无须插件登录)
|
* 打开项目(无须插件登录)
|
||||||
*/
|
*/
|
||||||
export async function openProjectWithoutLogging(hostname: string, port: number, username: string, path: string): Promise<void> {
|
export async function openProjectWithoutLogging(hostname: string, port: number, username: string, path: string): Promise<void> {
|
||||||
console.log(`[RemoteContainer] openProjectWithoutLogging called with:`, { hostname, port, username, path });
|
|
||||||
|
|
||||||
const command = `code --remote ssh-remote+${username}@${hostname}:${port} ${path} --reuse-window`;
|
const command = `code --remote ssh-remote+${username}@${hostname}:${port} ${path} --reuse-window`;
|
||||||
console.log(`[RemoteContainer] Command: ${command}`);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
|
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
|
||||||
terminal.show(true);
|
terminal.show(true);
|
||||||
terminal.sendText(command);
|
terminal.sendText(command);
|
||||||
console.log(`[RemoteContainer] openProjectWithoutLogging completed successfully`);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
console.error(`[RemoteContainer] Error in openProjectWithoutLogging:`, error);
|
|
||||||
vscode.window.showErrorMessage(`无登录打开项目失败: ${errorMessage}`);
|
vscode.window.showErrorMessage(`无登录打开项目失败: ${errorMessage}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user