cli: add option to enable --no-sleep for tunnel (#172043)

Fixes https://github.com/microsoft/vscode-remote-release/issues/7127

Also add auth logs for debugging, seemed like my OSS retained
a bad Github token.
This commit is contained in:
Connor Peet 2023-01-23 10:44:27 -08:00 committed by GitHub
parent 8cea434dec
commit 6d59c82ddc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 48 additions and 14 deletions

View file

@ -5,7 +5,7 @@
use crate::{
constants::{get_default_user_agent, PRODUCT_NAME_LONG},
info, log,
debug, info, log,
state::{LauncherPaths, PersistedState},
trace,
util::{
@ -112,7 +112,7 @@ pub struct StoredCredential {
}
impl StoredCredential {
pub async fn is_expired(&self, client: &reqwest::Client) -> bool {
pub async fn is_expired(&self, log: &log::Logger, client: &reqwest::Client) -> bool {
match self.provider {
AuthProvider::Microsoft => self
.expires_at
@ -122,14 +122,29 @@ impl StoredCredential {
// Make an auth request to Github. Mark the credential as expired
// only on a verifiable 4xx code. We don't error on any failed
// request since then a drop in connection could "require" a refresh
AuthProvider::Github => client
.get("https://api.github.com/user")
.header("Authorization", format!("token {}", self.access_token))
.header("User-Agent", get_default_user_agent())
.send()
.await
.map(|r| r.status().is_client_error())
.unwrap_or(false),
AuthProvider::Github => {
let res = client
.get("https://api.github.com/user")
.header("Authorization", format!("token {}", self.access_token))
.header("User-Agent", get_default_user_agent())
.send()
.await;
let res = match res {
Ok(r) => r,
Err(e) => {
warning!(log, "failed to check Github token: {}", e);
return false;
}
};
if res.status().is_success() {
return false;
}
let err = StatusError::from_res(res).await;
debug!(log, "github token looks expired: {:?}", err);
true
}
}
}
@ -453,7 +468,7 @@ impl Auth {
&self,
creds: &StoredCredential,
) -> Result<Option<StoredCredential>, AnyError> {
if !creds.is_expired(&self.client).await {
if !creds.is_expired(&self.log, &self.client).await {
return Ok(None);
}

View file

@ -63,6 +63,7 @@ export interface ConnectionInfo {
export const CONFIGURATION_KEY_PREFIX = 'remote.tunnels.access';
export const CONFIGURATION_KEY_HOST_NAME = CONFIGURATION_KEY_PREFIX + '.hostNameOverride';
export const CONFIGURATION_KEY_PREVENT_SLEEP = CONFIGURATION_KEY_PREFIX + '.preventSleep';
export const LOG_FILE_NAME = 'remoteTunnelService.log';
export const LOGGER_NAME = localize('remoteTunnelLog', "Remote Tunnel Service");

View file

@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CONFIGURATION_KEY_HOST_NAME, ConnectionInfo, IRemoteTunnelAccount, IRemoteTunnelService, LOGGER_NAME, LOG_CHANNEL_ID, LOG_FILE_NAME, TunnelStates, TunnelStatus } from 'vs/platform/remoteTunnel/common/remoteTunnel';
import { CONFIGURATION_KEY_HOST_NAME, CONFIGURATION_KEY_PREVENT_SLEEP, ConnectionInfo, IRemoteTunnelAccount, IRemoteTunnelService, LOGGER_NAME, LOG_CHANNEL_ID, LOG_FILE_NAME, TunnelStates, TunnelStatus } from 'vs/platform/remoteTunnel/common/remoteTunnel';
import { Emitter } from 'vs/base/common/event';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { INativeEnvironmentService } from 'vs/platform/environment/common/environment';
@ -30,6 +30,11 @@ type RemoteTunnelEnablementEvent = {
enabled: boolean;
};
const restartTunnelOnConfigurationChanges: readonly string[] = [
CONFIGURATION_KEY_HOST_NAME,
CONFIGURATION_KEY_PREVENT_SLEEP,
];
/**
* This service runs on the shared service. It is running the `code-tunnel` command
* to make the current machine available for remote access.
@ -82,7 +87,7 @@ export class RemoteTunnelService extends Disposable implements IRemoteTunnelServ
}));
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(CONFIGURATION_KEY_HOST_NAME)) {
if (restartTunnelOnConfigurationChanges.some(c => e.affectsConfiguration(c))) {
this._startTunnelProcessDelayer.trigger(() => this.updateTunnelProcess());
}
}));
@ -183,6 +188,9 @@ export class RemoteTunnelService extends Disposable implements IRemoteTunnelServ
} else {
args.push('--random-name');
}
if (this._preventSleep()) {
args.push('--no-sleep');
}
const serveCommand = this.runCodeTunneCommand('tunnel', args, (message: string, isErr: boolean) => {
if (isErr) {
this._logger.error(message);
@ -283,6 +291,10 @@ export class RemoteTunnelService extends Disposable implements IRemoteTunnelServ
return this._getHostName();
}
private _preventSleep() {
return !!this.configurationService.getValue<boolean>(CONFIGURATION_KEY_PREVENT_SLEEP);
}
private _getHostName(): string | undefined {
let name = this.configurationService.getValue<string>(CONFIGURATION_KEY_HOST_NAME) || hostname();
name = name.replace(/^-+/g, '').replace(/[^\w-]/g, '').substring(0, 20);

View file

@ -6,7 +6,7 @@
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { IProductService } from 'vs/platform/product/common/productService';
import { CONFIGURATION_KEY_HOST_NAME, CONFIGURATION_KEY_PREFIX, ConnectionInfo, IRemoteTunnelAccount, IRemoteTunnelService, LOGGER_NAME, LOG_CHANNEL_ID, LOG_FILE_NAME } from 'vs/platform/remoteTunnel/common/remoteTunnel';
import { CONFIGURATION_KEY_HOST_NAME, CONFIGURATION_KEY_PREFIX, CONFIGURATION_KEY_PREVENT_SLEEP, ConnectionInfo, IRemoteTunnelAccount, IRemoteTunnelService, LOGGER_NAME, LOG_CHANNEL_ID, LOG_FILE_NAME } from 'vs/platform/remoteTunnel/common/remoteTunnel';
import { AuthenticationSession, AuthenticationSessionsChangeEvent, IAuthenticationService } from 'vs/workbench/services/authentication/common/authentication';
import { localize } from 'vs/nls';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions, IWorkbenchContribution } from 'vs/workbench/common/contributions';
@ -756,6 +756,12 @@ Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).regis
patternErrorMessage: localize('remoteTunnelAccess.machineNameRegex', "The name must only consist of letters, numbers, underscore and dash. It must not start with a dash."),
maxLength: 20,
default: ''
},
[CONFIGURATION_KEY_PREVENT_SLEEP]: {
description: localize('remoteTunnelAccess.preventSleep', "Prevent the computer from sleeping when remote tunnel access is turned on."),
type: 'boolean',
scope: ConfigurationScope.MACHINE,
default: false,
}
}
});