Skip to content

Commit

Permalink
1.introduce the context to get ext version and provider version.
Browse files Browse the repository at this point in the history
2.adjust the getShell and getIntegratedShell to async to get the reqcli with provider version.
3.refactor the queryUserInfo method.
4.deactivate clear user when close vscode.
5.add warn msg when use without login.
6.reset terminal env when aksk is null.
  • Loading branch information
lyu571 committed Jan 8, 2024
1 parent 319dbeb commit 435fb27
Show file tree
Hide file tree
Showing 12 changed files with 176 additions and 164 deletions.
2 changes: 1 addition & 1 deletion package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"TcTerraform.pickup.aksk.placeholder": "Tencent Cloud {0}",
"TcTerraform.pickup.aksk.verify.empty": "{0} can not be empty",
"TcTerraform.welcome": "Welcome to use Tencent Cloud Terraform extension, please wait for the page loading...",
"TcTerraform.msg.aksk.notfound": "Cannot find TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY, please sign in first!",
"TcTerraform.msg.aksk.notfound": "Cannot find user info, please sign in first!",
"TcTerraform.login": "Login Tencent Cloud...",
"TcTerraform.login.msg.success": "Logged into Tencent Cloud successfully.",
"TcTerraform.login.msg.need.login": "Please log in Tencent Cloud first.",
Expand Down
28 changes: 3 additions & 25 deletions src/autocomplete/TerraformTipsProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ import { CompletionItemProvider, TextDocument, Position, CancellationToken, Comp
// import resources from '../../config/tips/tiat-resources.json';
import * as _ from "lodash";
import * as vscode from 'vscode';
import { executeCommandByExec } from "@/utils/cpUtils";
import * as fs from "fs";
import * as path from "path";
import * as workspaceUtils from "@/utils/workspaceUtils";
import * as TelemetryWrapper from "vscode-extension-telemetry-wrapper";
import * as context from "@/commons/context";

const LATEST_VERSION = "latest";
const versionPattern = /^v\d+(\.\d+){2}\.json$/;
let topLevelTypes = ["output", "provider", "resource", "variable", "data"];
let topLevelRegexes = topLevelTypes.map(o => {
Expand Down Expand Up @@ -422,26 +419,7 @@ function compareVersions(a, b) {

// load resource config from json files based on the appropriate version
async function loadResource(extPath: string): Promise<Tips> {
let tfVersion: string;
const cwd = workspaceUtils.getActiveEditorPath();
if (!cwd) {
TelemetryWrapper.sendError(Error("noWorkspaceSelected"));
console.error(`can not get path from active editor`);
}

await executeCommandByExec("terraform version", cwd).then(output => {
let match = RegExp(/tencentcloudstack\/tencentcloud (v\d+\.\d+\.\d+)/).exec(output);

if (match) {
tfVersion = match[1];
} else {
// gives the latest JSON if not tf provider version found
tfVersion = LATEST_VERSION;
}
console.log(`tf provider version:[${tfVersion}], cwd:[${cwd}]`);
}).catch(error => {
console.error(`execute terraform version failed: ${error}`);
});
const tfVersion = await context.getTfVersion();

let result: Tips | null = null;
const tipsDir = path.join(extPath, 'config', 'tips');
Expand All @@ -461,4 +439,4 @@ async function loadResource(extPath: string): Promise<Tips> {
// vscode.window.showInformationMessage(`Loaded json. tf version:[${tfVersion}], json version:[${result.version}]`);

return result;
}
}
36 changes: 23 additions & 13 deletions src/client/runner/terraformRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { terraformShellManager } from "../terminal/terraformShellManager";
import { executeCommand } from "../../utils/cpUtils";
import * as settingUtils from "../../utils/settingUtils";
import { openUrlHintOrNotShowAgain } from "../../utils/uiUtils";
import { localize } from "vscode-nls-i18n";


export class TerraformRunner extends BaseRunner {
Expand All @@ -32,20 +33,24 @@ export class TerraformRunner extends BaseRunner {
public async init(): Promise<any> {
console.debug("[DEBUG]#### TerraformRunner init begin.");

// this.setAKSK();
if (!checkAKSK()) {
return "plan abort";
}

terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Version);
terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Init);
(await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Version);
(await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Init);

return "init success";
}

public async executePlan(cwd: string, args: any): Promise<string> {
console.debug("[DEBUG]#### TerraformRunner executePlan begin.");

// this.setAKSK();
if (!checkAKSK()) {
return "plan abort";
}

terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Plan);
(await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Plan);

return "plan success";
}
Expand Down Expand Up @@ -112,7 +117,6 @@ export class TerraformRunner extends BaseRunner {
setCheckTerraformCmd(false);
});
}
return;
}

private async resetFileContent(tfFile: string, defaultContents: string) {
Expand All @@ -126,15 +130,9 @@ export class TerraformRunner extends BaseRunner {
public async resetTFState(resAddress: string) {
console.debug("[DEBUG]#### TerraformRunner resetTFState begin.");

await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance())
await (await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance()))
.runTerraformCmd(TerraformCommand.State, ['rm', '-lock=false', resAddress]);
}

private setAKSK(runner?: any) {
const [ak, sk, region] = settingUtils.getAKSKandRegion();
terraformShellManager.getIntegratedShell(runner).runNormalCmd("export TENCENTCLOUD_SECRET_ID=" + ak);
terraformShellManager.getIntegratedShell(runner).runNormalCmd("export TENCENTCLOUD_SECRET_KEY=" + sk);
}
}

export function getCheckTerraformCmd(): boolean {
Expand All @@ -144,3 +142,15 @@ export function getCheckTerraformCmd(): boolean {
export function setCheckTerraformCmd(checked: boolean): void {
vscode.workspace.getConfiguration().update("tcTerraform.checkTerraformCmd", checked);
}

export function checkAKSK(): boolean {
const [secretId, secretKey, _] = settingUtils.getAKSKandRegion();

if (secretId === undefined || secretKey === undefined || secretId === null || secretKey === null || secretId === '' || secretKey === '') {
let msg = localize("TcTerraform.msg.aksk.notfound");
console.error(msg);
vscode.window.showInformationMessage(msg);
return false;
}
return true;
}
4 changes: 4 additions & 0 deletions src/client/terminal/integratedShell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export class IntegratedShell extends BaseShell {
this.env = ee;
}

public getEnv() {
return this.env;
}

// Creates a png of terraform resource graph to visualize the resources under management.
public async visualize(): Promise<void> {
console.debug("[DEBUG]#### IntegratedShell visualize begin.");
Expand Down
44 changes: 26 additions & 18 deletions src/client/terminal/terraformShellManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,17 @@ import * as settingUtils from "../../utils/settingUtils";
import { Constants } from "../../commons/constants";

export interface ITerraformShellManager {
getShell(): BaseShell;
getShell(): Promise<BaseShell>;
// getCloudShell(): TCCloudShell;
getIntegratedShell(runner?: any): IntegratedShell;
getIntegratedShell(runner?: any): Promise<IntegratedShell>;
dispose(): void;
}



class TerraformShellManager implements ITerraformShellManager {
private static cloudShell = new TencentCloudShell();
private static integratedShell: IntegratedShell;

public getShell(): BaseShell {
public async getShell(): Promise<BaseShell> {
const isCloudShell: boolean = isTerminalSetToCloudShell();

TelemetryWrapper.addContextProperty("isCloudShell", isCloudShell.toString());
Expand All @@ -42,26 +40,36 @@ class TerraformShellManager implements ITerraformShellManager {
return TerraformShellManager.cloudShell;
}

public getIntegratedShell(runner?: any): IntegratedShell {
public async getIntegratedShell(runner?: any): Promise<IntegratedShell> {
if (!TerraformShellManager.integratedShell) {
// set TencentCloud AKSK, Region and Client info
const [ak, sk, region] = settingUtils.getAKSKandRegion();
const tfEnv = {
[Constants.REQUEST_CLIENT]: context.genRequestClient(),
[Constants.TENCENTCLOUD_SECRET_ID]: ak,
[Constants.TENCENTCLOUD_SECRET_KEY]: sk,
[Constants.TENCENTCLOUD_REGION]: region,
};
// default runner is Terraformer
TerraformShellManager.integratedShell = new IntegratedShell(TerraformerRunner.getInstance(), tfEnv);
// specify runner
if (runner) {
TerraformShellManager.integratedShell = new IntegratedShell(runner, tfEnv);
await this.initIntegratedShell(runner);
} else {
const curEnv = TerraformShellManager.integratedShell.getEnv();
// need to be reset if the current AKSK is undefined
if (!curEnv[Constants.TENCENTCLOUD_SECRET_ID] || !curEnv[Constants.TENCENTCLOUD_SECRET_KEY]) {
await this.initIntegratedShell(runner);
}
}
return TerraformShellManager.integratedShell;
}

private async initIntegratedShell(runner: any) {
const [ak, sk, region] = settingUtils.getAKSKandRegion();
const reqCli = await context.genRequestClient();
const tfEnv = {
[Constants.REQUEST_CLIENT]: reqCli, // set ReqCli for TIC Terminal
[Constants.TENCENTCLOUD_SECRET_ID]: ak,
[Constants.TENCENTCLOUD_SECRET_KEY]: sk,
[Constants.TENCENTCLOUD_REGION]: region,
};
// default runner is Terraformer
TerraformShellManager.integratedShell = new IntegratedShell(TerraformerRunner.getInstance(), tfEnv);
if (runner) {
TerraformShellManager.integratedShell = new IntegratedShell(runner, tfEnv);
}
}

public dispose(): void {
TerraformShellManager.cloudShell.dispose();
TerraformShellManager.integratedShell.dispose();
Expand Down
38 changes: 34 additions & 4 deletions src/commons/context.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { container } from './container';
import * as vscode from 'vscode';
import * as workspaceUtils from "@/utils/workspaceUtils";
import * as cpUtils from "@/utils/cpUtils";
import * as TelemetryWrapper from "vscode-extension-telemetry-wrapper";

export const Context = Symbol('ExtensionContext');
export const REQUEST_CLIENT_PREFIX = "Terraform-Vscode-";//Terraform-1.81.61@vscode";
export const REQUEST_CLIENT_PREFIX = "Terraform-";//Terraform-1.81.61@vscode";
const LATEST_VERSION = "latest";

export function bindExtensionContext(ctx: vscode.ExtensionContext) {
container.bind(Context).toConstantValue(ctx);
Expand All @@ -14,8 +19,33 @@ export function getExtensionVersion(): string {
return currentVersion;
}

export function genRequestClient(): string {
const currentVersion = getExtensionVersion();
const reqCli = `${REQUEST_CLIENT_PREFIX}v${currentVersion}`;
export async function genRequestClient(): Promise<string> {
const extVersion = getExtensionVersion();
const tfVersion = await getTfVersion() || LATEST_VERSION;
const reqCli = `${REQUEST_CLIENT_PREFIX}${tfVersion}@vscode-v${extVersion}`;
return reqCli;
}

export async function getTfVersion(): Promise<string> {
let tfVersion = '';
const cwd = workspaceUtils.getActiveEditorPath();
if (!cwd) {
TelemetryWrapper.sendError(Error("noWorkspaceSelected"));
console.error(`can not get path from active editor`);
}

await cpUtils.executeCommandByExec("terraform version", cwd).then(output => {
let match = RegExp(/tencentcloudstack\/tencentcloud (v\d+\.\d+\.\d+)/).exec(output);

if (match) {
tfVersion = match[1];
} else {
// gives the latest JSON if not tf provider version found
tfVersion = LATEST_VERSION;
}
console.log(`[DEBUG]getTfVersion tf provider version:[${tfVersion}], cwd:[${cwd}]`);
}).catch(error => {
console.error(`execute terraform version failed: ${error}`);
});
return tfVersion;
}
12 changes: 6 additions & 6 deletions src/commons/customCmdRegister.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,16 @@ export function regHelpCommands() {
}

export function regResourceRelatedCommands() {
commands.registerCommand(cmds.executeTferImport, function (param: any) {
terraformShellManager.getIntegratedShell(TerraformerRunner.getInstance()).import(param, param.fileName);
commands.registerCommand(cmds.executeTferImport, async function (param: any) {
(await terraformShellManager.getIntegratedShell(TerraformerRunner.getInstance())).import(param, param.fileName);
});

commands.registerCommand("tcTerraform.init", function (param: any) {
terraformShellManager.getIntegratedShell(TerraformRunner.getInstance()).init();
commands.registerCommand("tcTerraform.init", async function (param: any) {
(await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance())).init();
});

commands.registerCommand("tcTerraform.plan", function (param: any) {
terraformShellManager.getIntegratedShell(TerraformRunner.getInstance()).plan(param);
commands.registerCommand("tcTerraform.plan", async function (param: any) {
(await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance())).plan(param);
});

commands.registerCommand(resourceRefresh, function (param: any) {
Expand Down
1 change: 0 additions & 1 deletion src/commons/tencent/user/auth/credentail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import MultiStepInput from "../../../multiStepInput";
import { Credential } from "tencentcloud-sdk-nodejs/tencentcloud/common/interface";
import { localize } from "vscode-nls-i18n";
import constant from "../index";
import * as vscode from "vscode";

export async function getCredentailByInput() {
const defaultRegion = "ap-guangzhou";
Expand Down
Loading

0 comments on commit 435fb27

Please sign in to comment.