Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecate and migrate old environment variable settings #3555

Merged
merged 7 commits into from
Jul 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 11 additions & 36 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2231,39 +2231,17 @@
"default": 10,
"description": "%vscode-docker.config.docker.truncateMaxLength%"
},
"docker.dockerodeOptions": {
"containers.environment": {
"type": "object",
"description": "%vscode-docker.config.docker.dockerodeOptions%"
},
"docker.host": {
"type": "string",
"default": "",
"description": "%vscode-docker.config.docker.host%",
"scope": "machine-overridable"
},
"docker.context": {
"type": "string",
"default": "",
"description": "%vscode-docker.config.docker.context%",
"scope": "machine-overridable"
},
"docker.certPath": {
"type": "string",
"default": "",
"description": "%vscode-docker.config.docker.certPath%",
"scope": "machine-overridable"
},
"docker.tlsVerify": {
"type": "string",
"default": "",
"description": "%vscode-docker.config.docker.tlsVerify%",
"additionalProperties": {
"type": "string"
},
"description": "%vscode-docker.config.containers.environment%",
"scope": "machine-overridable"
},
"docker.machineName": {
"type": "string",
"default": "",
"description": "%vscode-docker.config.docker.machineName%",
"scope": "machine-overridable"
"docker.dockerodeOptions": {
bwateratmsft marked this conversation as resolved.
Show resolved Hide resolved
"type": "object",
"description": "%vscode-docker.config.docker.dockerodeOptions%"
},
"docker.languageserver.diagnostics.deprecatedMaintainer": {
"scope": "resource",
Expand Down Expand Up @@ -3081,14 +3059,11 @@
"docker.commands.logs",
"docker.commands.composeUp",
"docker.commands.composeDown",
"containers.environment",
"docker.dockerodeOptions",
"docker.host",
"docker.context",
"docker.certPath",
"docker.tlsVerify",
"docker.machineName",
"docker.scaffolding.templatePath",
"docker.dockerPath"
"docker.dockerPath",
"docker.composeCommand"
bwateratmsft marked this conversation as resolved.
Show resolved Hide resolved
]
}
},
Expand Down
6 changes: 1 addition & 5 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -177,12 +177,8 @@
"vscode-docker.config.docker.imageBuildContextPath": "Build context PATH to pass to Docker build command.",
"vscode-docker.config.docker.truncateLongRegistryPaths": "Set to true to truncate long image and container registry paths in Docker view",
"vscode-docker.config.docker.truncateMaxLength": "Maximum length of a registry paths displayed in Docker view, including ellipsis. The truncateLongRegistryPaths setting must be set to true for truncateMaxLength setting to be effective.",
"vscode-docker.config.containers.environment": "Environment variables that will be applied to all VS Code terminals and to all background processes started by the Docker extension. Use for variables like `DOCKER_HOST`, etc.",
"vscode-docker.config.docker.dockerodeOptions": "If specified, this object will be passed to the Dockerode constructor. Takes precedence over DOCKER_HOST, the Docker Host setting, and any existing Docker contexts.",
"vscode-docker.config.docker.host": "Equivalent to setting the DOCKER_HOST environment variable, for example, ssh://myuser@mymachine or tcp://1.2.3.4.",
"vscode-docker.config.docker.context": "Equivalent to setting the DOCKER_CONTEXT environment variable.",
"vscode-docker.config.docker.certPath": "Equivalent to setting the DOCKER_CERT_PATH environment variable.",
"vscode-docker.config.docker.tlsVerify": "Equivalent to setting the DOCKER_TLS_VERIFY environment variable.",
"vscode-docker.config.docker.machineName": "Equivalent to setting the DOCKER_MACHINE_NAME environment variable.",
"vscode-docker.config.docker.languageserver.diagnostics.deprecatedMaintainer": "Controls the diagnostic severity for the deprecated MAINTAINER instruction",
"vscode-docker.config.docker.languageserver.diagnostics.emptyContinuationLine": "Controls the diagnostic severity for flagging empty continuation lines found in instructions that span multiple lines",
"vscode-docker.config.docker.languageserver.diagnostics.directiveCasing": "Controls the diagnostic severity for parser directives that are not written in lowercase",
Expand Down
17 changes: 9 additions & 8 deletions src/docker/ContextManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ export class DockerContextManager implements ContextManager, Disposable {
this.tryGetContextFromEnvironment(actionContext) ||
this.tryGetContextFromFilesystemClues(actionContext);

// A result from any of these three implies that there is only one context, or it is fixed by `docker.host` / `DOCKER_HOST`, or `docker.context` / `DOCKER_CONTEXT`
// A result from any of these three implies that there is only one context, or it is fixed by `[containers.environment.]DOCKER_HOST`, or `[containers.environment.]DOCKER_CONTEXT`
// As such, we will lock to the current context
// Otherwise, unlock in case we were previously locked
if (fixedContext) {
Expand Down Expand Up @@ -311,20 +311,21 @@ export class DockerContextManager implements ContextManager, Disposable {
}

private tryGetContextFromSettings(actionContext: IActionContext): DockerContext | undefined | string {
const config = workspace.getConfiguration('docker');
const config = workspace.getConfiguration('containers');
let dockerHost: string | undefined;
let dockerContext: string | undefined;
const environment = config.get('environment', {});

if ((dockerHost = config.get('host'))) { // Assignment + check is intentional
actionContext.telemetry.properties.hostSource = 'docker.host';
if ((dockerHost = environment['DOCKER_HOST'])) { // Assignment + check is intentional
actionContext.telemetry.properties.hostSource = 'containers.environment.host';

return {
...defaultContext,
Current: true,
DockerEndpoint: dockerHost,
} as DockerContext;
} else if ((dockerContext = config.get('context'))) { // Assignment + check is intentional
actionContext.telemetry.properties.hostSource = 'docker.context';
} else if ((dockerContext = environment['DOCKER_CONTEXT'])) { // Assignment + check is intentional
actionContext.telemetry.properties.hostSource = 'containers.environment.context';

return dockerContext;
}
Expand Down Expand Up @@ -442,13 +443,13 @@ export class DockerContextManager implements ContextManager, Disposable {
// If URL parsing fails, let's catch it and give a better error message to help users from a common mistake
actionContext.telemetry.properties.hostProtocol = 'unknown';
const message =
localize('vscode-docker.docker.contextManager.invalidHostSetting', 'The value provided for the setting `docker.host` or environment variable `DOCKER_HOST` is invalid. It must include the protocol, for example, ssh://myuser@mymachine or tcp://1.2.3.4.');
localize('vscode-docker.docker.contextManager.invalidHostSetting', 'The value provided for the setting `containers.environment.DOCKER_HOST` or environment variable `DOCKER_HOST` is invalid. It must include the protocol, for example, ssh://myuser@mymachine or tcp://1.2.3.4.');
const button = localize('vscode-docker.docker.contextManager.openSettings', 'Open Settings');

void window.showErrorMessage(message, button)
.then((result: string) => {
if (result === button) {
void commands.executeCommand('workbench.action.openSettings', 'docker.host');
void commands.executeCommand('workbench.action.openSettings', 'containers.environment');
}
});

Expand Down
29 changes: 24 additions & 5 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { registerTrees } from './tree/registerTrees';
import { AzureAccountExtensionListener } from './utils/AzureAccountExtensionListener';
import { cryptoUtils } from './utils/cryptoUtils';
import { DocumentSettingsClientFeature } from './utils/DocumentSettingsClientFeature';
import { migrateOldEnvironmentSettingsIfNeeded } from './utils/migrateOldEnvironmentSettingsIfNeeded';
import { isLinux, isMac, isWindows } from './utils/osUtils';

export type KeyInfo = { [keyName: string]: string };
Expand Down Expand Up @@ -60,6 +61,9 @@ export async function activateInternal(ctx: vscode.ExtensionContext, perfStats:
activateContext.telemetry.measurements.mainFileLoad = (perfStats.loadEndTime - perfStats.loadStartTime) / 1000;
activateContext.telemetry.properties.dockerInstallationIDHash = await getDockerInstallationIDHash();

// Set up environment variables
setEnvironmentVariableContributions(ctx);

// All of these internally handle telemetry opt-in
ext.activityMeasurementService = new ActivityMeasurementService(ctx.globalState);
ext.experimentationService = await createExperimentationService(
Expand Down Expand Up @@ -111,6 +115,9 @@ export async function activateInternal(ctx: vscode.ExtensionContext, perfStats:
registerListeners();
});

// If this call results in changes to the values, the settings listener set up below will automatically re-update
void migrateOldEnvironmentSettingsIfNeeded();

// If the magic VSCODE_DOCKER_TEAM environment variable is set to 1, export the mementos for use by the Memento Explorer extension
if (process.env.VSCODE_DOCKER_TEAM === '1') {
return {
Expand Down Expand Up @@ -190,13 +197,14 @@ namespace Configuration {
settings: null
});

// Reset extension environment variables contribution if needed
if (e.affectsConfiguration('containers.environment')) {
setEnvironmentVariableContributions(ext.context);
}

// These settings will result in a need to change context that doesn't actually change the docker context
// So, force a manual refresh so the settings get picked up
if (e.affectsConfiguration('docker.host') ||
e.affectsConfiguration('docker.context') ||
e.affectsConfiguration('docker.certPath') ||
e.affectsConfiguration('docker.tlsVerify') ||
e.affectsConfiguration('docker.machineName') ||
if (e.affectsConfiguration('containers.environment') ||
e.affectsConfiguration('docker.dockerodeOptions') ||
e.affectsConfiguration('docker.dockerPath') ||
e.affectsConfiguration('docker.composeCommand')) {
Expand All @@ -208,6 +216,17 @@ namespace Configuration {
}
/* eslint-enable @typescript-eslint/no-namespace, no-inner-declarations */

function setEnvironmentVariableContributions(ctx: vscode.ExtensionContext): void {
const settingValue: NodeJS.ProcessEnv = vscode.workspace.getConfiguration('containers').get<NodeJS.ProcessEnv>('environment', {});

ctx.environmentVariableCollection.clear();
ctx.environmentVariableCollection.persistent = true;

for (const key of Object.keys(settingValue)) {
ctx.environmentVariableCollection.replace(key, settingValue[key]);
bwateratmsft marked this conversation as resolved.
Show resolved Hide resolved
}
}

function activateDockerfileLanguageClient(ctx: vscode.ExtensionContext): void {
// Don't wait
void callWithTelemetryAndErrorHandling('docker.languageclient.activate', async (context: IActionContext) => {
Expand Down
26 changes: 5 additions & 21 deletions src/utils/addDockerSettingsToEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,14 @@
*--------------------------------------------------------------------------------------------*/

import { workspace } from 'vscode';
import { configPrefix } from '../constants';
import { ext } from '../extensionVariables';
import { localize } from '../localize';

export function addDockerSettingsToEnv(env: NodeJS.ProcessEnv, oldEnv: NodeJS.ProcessEnv): void {
addDockerSettingToEnv("host", 'DOCKER_HOST', env, oldEnv);
addDockerSettingToEnv("context", 'DOCKER_CONTEXT', env, oldEnv);
addDockerSettingToEnv("certPath", 'DOCKER_CERT_PATH', env, oldEnv);
addDockerSettingToEnv("tlsVerify", 'DOCKER_TLS_VERIFY', env, oldEnv);
addDockerSettingToEnv("machineName", 'DOCKER_MACHINE_NAME', env, oldEnv);
}

function addDockerSettingToEnv(settingKey: string, envVar: string, env: NodeJS.ProcessEnv, oldEnv: NodeJS.ProcessEnv): void {
const value = workspace.getConfiguration(configPrefix).get<string>(settingKey, '');

const expectedType = "string";
const actualType = typeof value;
if (expectedType !== actualType) {
ext.outputChannel.appendLine(localize('vscode-docker.utils.env.ignoring', 'WARNING: Ignoring setting "{0}.{1}" because type "{2}" does not match expected type "{3}".', configPrefix, settingKey, actualType, expectedType));
bwateratmsft marked this conversation as resolved.
Show resolved Hide resolved
} else if (value) {
if (oldEnv[envVar] && oldEnv[envVar] !== value) {
ext.outputChannel.appendLine(localize('vscode-docker.utils.env.overwriting', 'WARNING: Overwriting environment variable "{0}" with VS Code setting "{1}.{2}".', envVar, configPrefix, settingKey));
}
export function addDockerSettingsToEnv(newEnv: NodeJS.ProcessEnv, oldEnv: NodeJS.ProcessEnv): void {
const environmentSettings: NodeJS.ProcessEnv = workspace.getConfiguration('containers').get<NodeJS.ProcessEnv>('environment', {});

env[envVar] = value;
for (const key of Object.keys(environmentSettings)) {
ext.outputChannel.appendLine(localize('vscode-docker.utils.env.overwriting', 'WARNING: Overwriting environment variable "{0}" from VS Code setting "containers.environment".', key));
newEnv[key] = environmentSettings[key];
}
}
116 changes: 116 additions & 0 deletions src/utils/migrateOldEnvironmentSettingsIfNeeded.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE.md in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { DialogResponses } from '@microsoft/vscode-azext-utils';
import * as vscode from 'vscode';
import { localize } from '../localize';
import { cloneObject } from './cloneObject';

const oldSettingsMap = {
'host': 'DOCKER_HOST',
'context': 'DOCKER_CONTEXT',
'certPath': 'DOCKER_CERT_PATH',
'tlsVerify': 'DOCKER_TLS_VERIFY',
'machineName': 'DOCKER_MACHINE_NAME',
};

export async function migrateOldEnvironmentSettingsIfNeeded(): Promise<void> {
const oldConfig = vscode.workspace.getConfiguration('docker');
const newConfig = vscode.workspace.getConfiguration('containers');

let alreadyPrompted = false;
for (const oldSetting of Object.keys(oldSettingsMap)) {
const settingValue: string | undefined = oldConfig.get<string>(oldSetting);

// If any config target has a value, we'll attempt to migrate all three config sections as needed
if (settingValue) {
// Prompt if we haven't already
if (!alreadyPrompted) {
const response = await vscode.window.showWarningMessage(
localize('vscode-docker.checkForOldEnvironmentSettings.prompt', 'Some of your Docker extension settings have been renamed. Would you like us to migrate them for you?'),
DialogResponses.yes,
DialogResponses.no
);

if (response === DialogResponses.yes) {
alreadyPrompted = true;
} else {
return;
}
}

const newSetting = oldSettingsMap[oldSetting];
await migrateOldEnvironmentSetting(oldConfig, oldSetting, newConfig, newSetting);
}
}
}

async function migrateOldEnvironmentSetting(
oldConfig: vscode.WorkspaceConfiguration,
oldSetting: string,
newConfig: vscode.WorkspaceConfiguration,
newSetting: string
): Promise<void> {
const oldValueInspection = oldConfig.inspect<string>(oldSetting);
const newValueInspection = newConfig.inspect<NodeJS.ProcessEnv>('environment');

// Migrate the global AKA user setting
await migrateOldEnvironmentSettingForTarget(
oldConfig,
oldSetting,
oldValueInspection.globalValue,
newConfig,
newSetting,
newValueInspection.globalValue,
vscode.ConfigurationTarget.Global
);

// Migrate the workspace setting
await migrateOldEnvironmentSettingForTarget(
oldConfig,
oldSetting,
oldValueInspection.workspaceValue,
newConfig,
newSetting,
newValueInspection.workspaceValue,
vscode.ConfigurationTarget.Workspace
);

// Migrate the workspace folder setting
await migrateOldEnvironmentSettingForTarget(
oldConfig,
oldSetting,
oldValueInspection.workspaceFolderValue,
newConfig,
newSetting,
newValueInspection.workspaceFolderValue,
vscode.ConfigurationTarget.WorkspaceFolder
);
}

async function migrateOldEnvironmentSettingForTarget(
oldConfig: vscode.WorkspaceConfiguration,
oldSetting: string,
oldValue: string | undefined,
newConfig: vscode.WorkspaceConfiguration,
newSetting: string,
newValue: NodeJS.ProcessEnv | undefined,
target: vscode.ConfigurationTarget
): Promise<void> {
// If no value was set in this particular target, skip
if (!oldValue) {
return;
}

// Remove the old setting from this target
await oldConfig.update(oldSetting, undefined, target);

// Append the old value to the current environment object for this target
newValue = cloneObject(newValue ?? {});
newValue[newSetting] = oldValue;

// Update the new setting for this target
await newConfig.update('environment', newValue, target);
}