forked from vscode-kubernetes-tools/vscode-kubernetes-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubectl.ts
279 lines (247 loc) · 11.7 KB
/
kubectl.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import { Terminal, Disposable } from 'vscode';
import { ChildProcess, spawn as spawnChildProcess } from "child_process";
import { Host } from './host';
import { FS } from './fs';
import { Shell, ShellHandler, ShellResult } from './shell';
import * as binutil from './binutil';
import { Errorable } from './errorable';
import { parseLineOutput } from './outputUtils';
import * as compatibility from './components/kubectl/compatibility';
import { getToolPath, affectsUs } from './components/config/config';
const KUBECTL_OUTPUT_COLUMN_SEPARATOR = /\s+/g;
export interface Kubectl {
checkPresent(errorMessageMode: CheckPresentMessageMode): Promise<boolean>;
invoke(command: string, handler?: ShellHandler): Promise<void>;
invokeWithProgress(command: string, progressMessage: string, handler?: ShellHandler): Promise<void>;
invokeAsync(command: string, stdin?: string): Promise<ShellResult>;
invokeAsyncWithProgress(command: string, progressMessage: string): Promise<ShellResult>;
spawnAsChild(command: string[]): Promise<ChildProcess>;
/**
* Invoke a kubectl command in Terminal.
* @param command the subcommand to run.
* @param terminalName if empty, run the command in the shared Terminal; otherwise run it in a new Terminal.
*/
invokeInNewTerminal(command: string, terminalName: string, onClose?: (e: Terminal) => any, pipeTo?: string): Promise<Disposable>;
invokeInSharedTerminal(command: string): Promise<void>;
runAsTerminal(command: string[], terminalName: string): Promise<void>;
asLines(command: string): Promise<Errorable<string[]>>;
fromLines(command: string): Promise<Errorable<{ [key: string]: string }[]>>;
asJson<T>(command: string): Promise<Errorable<T>>;
}
interface Context {
readonly host: Host;
readonly fs: FS;
readonly shell: Shell;
readonly installDependenciesCallback: () => void;
binFound: boolean;
binPath: string;
}
class KubectlImpl implements Kubectl {
constructor(host: Host, fs: FS, shell: Shell, installDependenciesCallback: () => void, kubectlFound: boolean) {
this.context = { host : host, fs : fs, shell : shell, installDependenciesCallback : installDependenciesCallback, binFound : kubectlFound, binPath : 'kubectl' };
}
private readonly context: Context;
private sharedTerminal: Terminal;
checkPresent(errorMessageMode: CheckPresentMessageMode): Promise<boolean> {
return checkPresent(this.context, errorMessageMode);
}
invoke(command: string, handler?: ShellHandler): Promise<void> {
return invoke(this.context, command, handler);
}
invokeWithProgress(command: string, progressMessage: string, handler?: ShellHandler): Promise<void> {
return invokeWithProgress(this.context, command, progressMessage, handler);
}
invokeAsync(command: string, stdin?: string): Promise<ShellResult> {
return invokeAsync(this.context, command, stdin);
}
invokeAsyncWithProgress(command: string, progressMessage: string): Promise<ShellResult> {
return invokeAsyncWithProgress(this.context, command, progressMessage);
}
spawnAsChild(command: string[]): Promise<ChildProcess> {
return spawnAsChild(this.context, command);
}
async invokeInNewTerminal(command: string, terminalName: string, onClose?: (e: Terminal) => any, pipeTo?: string): Promise<Disposable> {
const terminal = this.context.host.createTerminal(terminalName);
const disposable = onClose ? this.context.host.onDidCloseTerminal(onClose) : null;
await invokeInTerminal(this.context, command, pipeTo, terminal);
return disposable;
}
invokeInSharedTerminal(command: string, terminalName?: string): Promise<void> {
const terminal = this.getSharedTerminal();
return invokeInTerminal(this.context, command, undefined, terminal);
}
runAsTerminal(command: string[], terminalName: string): Promise<void> {
return runAsTerminal(this.context, command, terminalName);
}
asLines(command: string): Promise<Errorable<string[]>> {
return asLines(this.context, command);
}
fromLines(command: string): Promise<Errorable<{ [key: string]: string }[]>> {
return fromLines(this.context, command);
}
asJson<T>(command: string): Promise<Errorable<T>> {
return asJson(this.context, command);
}
private getSharedTerminal(): Terminal {
if (!this.sharedTerminal) {
this.sharedTerminal = this.context.host.createTerminal('kubectl');
const disposable = this.context.host.onDidCloseTerminal((terminal) => {
if (terminal === this.sharedTerminal) {
this.sharedTerminal = null;
disposable.dispose();
}
});
this.context.host.onDidChangeConfiguration((change) => {
if (affectsUs(change) && this.sharedTerminal) {
this.sharedTerminal.dispose();
}
});
}
return this.sharedTerminal;
}
}
export function create(host: Host, fs: FS, shell: Shell, installDependenciesCallback: () => void): Kubectl {
return new KubectlImpl(host, fs, shell, installDependenciesCallback, false);
}
export enum CheckPresentMessageMode {
Command,
Activation,
Silent,
}
async function checkPresent(context: Context, errorMessageMode: CheckPresentMessageMode): Promise<boolean> {
if (context.binFound) {
return true;
}
return await checkForKubectlInternal(context, errorMessageMode);
}
async function checkForKubectlInternal(context: Context, errorMessageMode: CheckPresentMessageMode): Promise<boolean> {
const binName = 'kubectl';
const bin = getToolPath(context.host, context.shell, binName);
const contextMessage = getCheckKubectlContextMessage(errorMessageMode);
const inferFailedMessage = `Could not find "${binName}" binary.${contextMessage}`;
const configuredFileMissingMessage = `${bin} does not exist! ${contextMessage}`;
return await binutil.checkForBinary(context, bin, binName, inferFailedMessage, configuredFileMissingMessage, errorMessageMode !== CheckPresentMessageMode.Silent);
}
function getCheckKubectlContextMessage(errorMessageMode: CheckPresentMessageMode): string {
if (errorMessageMode === CheckPresentMessageMode.Activation) {
return ' Kubernetes commands other than configuration will not function correctly.';
} else if (errorMessageMode === CheckPresentMessageMode.Command) {
return ' Cannot execute command.';
}
return '';
}
async function invoke(context: Context, command: string, handler?: ShellHandler): Promise<void> {
await kubectlInternal(context, command, handler || kubectlDone(context));
}
async function invokeWithProgress(context: Context, command: string, progressMessage: string, handler?: ShellHandler): Promise<void> {
return context.host.withProgress((p) => {
return new Promise<void>((resolve, reject) => {
p.report({ message: progressMessage });
kubectlInternal(context, command, (code, stdout, stderr) => {
resolve();
(handler || kubectlDone(context))(code, stdout, stderr);
});
});
});
}
async function invokeAsync(context: Context, command: string, stdin?: string): Promise<ShellResult> {
if (await checkPresent(context, CheckPresentMessageMode.Command)) {
const bin = baseKubectlPath(context);
const cmd = `${bin} ${command}`;
const sr = await context.shell.exec(cmd, stdin);
if (sr.code !== 0) {
checkPossibleIncompatibility(context);
}
return sr;
} else {
return { code: -1, stdout: '', stderr: '' };
}
}
async function checkPossibleIncompatibility(context: Context): Promise<void> {
const compat = await compatibility.check((cmd) => asJson<compatibility.Version>(context, cmd));
if (!compatibility.isGuaranteedCompatible(compat) && compat.didCheck) {
const versionAlert = `kubectl version ${compat.clientVersion} may be incompatible with cluster Kubernetes version ${compat.serverVersion}`;
context.host.showWarningMessage(versionAlert);
}
}
async function invokeAsyncWithProgress(context: Context, command: string, progressMessage: string): Promise<ShellResult> {
return context.host.withProgress(async (p) => {
p.report({ message: progressMessage });
return await invokeAsync(context, command);
});
}
async function spawnAsChild(context: Context, command: string[]): Promise<ChildProcess> {
if (await checkPresent(context, CheckPresentMessageMode.Command)) {
return spawnChildProcess(path(context), command, context.shell.execOpts());
}
}
async function invokeInTerminal(context: Context, command: string, pipeTo: string | undefined, terminal: Terminal): Promise<void> {
if (await checkPresent(context, CheckPresentMessageMode.Command)) {
const kubectlCommand = `kubectl ${command}`;
const fullCommand = pipeTo ? `${kubectlCommand} | ${pipeTo}` : kubectlCommand;
terminal.sendText(fullCommand);
terminal.show();
}
}
async function runAsTerminal(context: Context, command: string[], terminalName: string): Promise<void> {
if (await checkPresent(context, CheckPresentMessageMode.Command)) {
const term = context.host.createTerminal(terminalName, path(context), command);
term.show();
}
}
async function kubectlInternal(context: Context, command: string, handler: ShellHandler): Promise<void> {
if (await checkPresent(context, CheckPresentMessageMode.Command)) {
const bin = baseKubectlPath(context);
const cmd = `${bin} ${command}`;
context.shell.exec(cmd, null).then(({code, stdout, stderr}) => handler(code, stdout, stderr));
}
}
function kubectlDone(context: Context): ShellHandler {
return (result: number, stdout: string, stderr: string) => {
if (result !== 0) {
context.host.showErrorMessage('Kubectl command failed: ' + stderr);
console.log(stderr);
checkPossibleIncompatibility(context);
return;
}
context.host.showInformationMessage(stdout);
};
}
function baseKubectlPath(context: Context): string {
let bin = getToolPath(context.host, context.shell, 'kubectl');
if (!bin) {
bin = 'kubectl';
}
return bin;
}
async function asLines(context: Context, command: string): Promise<Errorable<string[]>> {
const shellResult = await invokeAsync(context, command);
if (shellResult.code === 0) {
let lines = shellResult.stdout.split('\n');
lines.shift();
lines = lines.filter((l) => l.length > 0);
return { succeeded: true, result: lines };
}
return { succeeded: false, error: [ shellResult.stderr ] };
}
async function fromLines(context: Context, command: string): Promise<Errorable<{ [key: string]: string }[]>> {
const shellResult = await invokeAsync(context, command);
if (shellResult.code === 0) {
let lines = shellResult.stdout.split('\n');
lines = lines.filter((l) => l.length > 0);
const parsedOutput = parseLineOutput(lines, KUBECTL_OUTPUT_COLUMN_SEPARATOR);
return { succeeded: true, result: parsedOutput };
}
return { succeeded: false, error: [ shellResult.stderr ] };
}
async function asJson<T>(context: Context, command: string): Promise<Errorable<T>> {
const shellResult = await invokeAsync(context, command);
if (shellResult.code === 0) {
return { succeeded: true, result: JSON.parse(shellResult.stdout.trim()) as T };
}
return { succeeded: false, error: [ shellResult.stderr ] };
}
function path(context: Context): string {
const bin = baseKubectlPath(context);
return binutil.execPath(context.shell, bin);
}