forked from vscode-kubernetes-tools/vscode-kubernetes-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubectlUtils.ts
328 lines (293 loc) · 12.5 KB
/
kubectlUtils.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import * as vscode from "vscode";
import { Kubectl } from "./kubectl";
import { kubeChannel } from "./kubeChannel";
import { sleep } from "./sleep";
import { ObjectMeta, KubernetesCollection, DataResource, Namespace, Pod, KubernetesResource } from './kuberesources.objectmodel';
import { failed } from "./errorable";
export interface KubectlContext {
readonly clusterName: string;
readonly contextName: string;
readonly userName: string;
readonly active: boolean;
}
export interface KubernetesObject {
readonly name: string;
}
export interface NamespaceInfo extends KubernetesObject {
readonly active: boolean;
}
export interface HasSelector extends KubernetesObject {
readonly selector: object;
}
export interface PodInfo extends KubernetesObject {
readonly namespace: string;
readonly nodeName: string;
readonly status: string;
}
export interface ClusterConfig {
readonly server: string;
readonly certificateAuthority: string;
}
export interface DataHolder {
readonly metadata: ObjectMeta;
readonly data: any;
}
async function getKubeconfig(kubectl: Kubectl): Promise<any> {
const shellResult = await kubectl.asJson<any>("config view -o json");
if (failed(shellResult)) {
vscode.window.showErrorMessage(shellResult.error[0]);
return null;
}
return shellResult.result;
}
export async function getCurrentClusterConfig(kubectl: Kubectl): Promise<ClusterConfig | undefined> {
const kubeConfig = await getKubeconfig(kubectl);
if (!kubeConfig) {
return undefined;
}
const contextConfig = kubeConfig.contexts.find((context) => context.name === kubeConfig["current-context"]);
const clusterConfig = kubeConfig.clusters.find((cluster) => cluster.name === contextConfig.context.cluster);
return {
server: clusterConfig.cluster.server,
certificateAuthority: clusterConfig.cluster["certificate-authority"]
};
}
export async function getContexts(kubectl: Kubectl): Promise<KubectlContext[]> {
const kubectlConfig = await getKubeconfig(kubectl);
if (!kubectlConfig) {
return [];
}
const currentContext = kubectlConfig["current-context"];
const contexts = kubectlConfig.contexts;
return contexts.map((c) => {
return {
clusterName: c.context.cluster,
contextName: c.name,
userName: c.context.user,
active: c.name === currentContext
};
});
}
export async function deleteCluster(kubectl: Kubectl, cluster: KubectlContext): Promise<boolean> {
const deleteClusterResult = await kubectl.invokeAsyncWithProgress(`config delete-cluster ${cluster.clusterName}`, "Deleting cluster...");
if (deleteClusterResult.code !== 0) {
kubeChannel.showOutput(`Failed to delete the specified cluster ${cluster.clusterName} from the kubeconfig: ${deleteClusterResult.stderr}`, `Delete ${cluster.contextName}`);
vscode.window.showErrorMessage(`Delete ${cluster.contextName} failed. See Output window for more details.`);
return false;
}
const deleteUserResult = await kubectl.invokeAsyncWithProgress(`config unset users.${cluster.userName}`, "Deleting user...");
if (deleteUserResult.code !== 0) {
kubeChannel.showOutput(`Failed to delete user info for context ${cluster.contextName} from the kubeconfig: ${deleteUserResult.stderr}`);
vscode.window.showErrorMessage(`Delete ${cluster.contextName} Failed. See Output window for more details.`);
return false;
}
const deleteContextResult = await kubectl.invokeAsyncWithProgress(`config delete-context ${cluster.contextName}`, "Deleting context...");
if (deleteContextResult.code !== 0) {
kubeChannel.showOutput(`Failed to delete the specified cluster's context ${cluster.contextName} from the kubeconfig: ${deleteContextResult.stderr}`);
vscode.window.showErrorMessage(`Delete ${cluster.contextName} Failed. See Output window for more details.`);
return false;
}
vscode.window.showInformationMessage(`Deleted context '${cluster.contextName}' and associated data from the kubeconfig.`);
return true;
}
export async function getDataHolders(resource: string, kubectl: Kubectl): Promise<DataHolder[]> {
const currentNS = await currentNamespace(kubectl);
const depList = await kubectl.asJson<KubernetesCollection<DataResource>>(`get ${resource} -o json --namespace=${currentNS}`);
if (failed(depList)) {
vscode.window.showErrorMessage(depList.error[0]);
return [];
}
return depList.result.items;
}
export async function getGlobalResources(kubectl: Kubectl, resource: string): Promise<KubernetesResource[]> {
const rsrcs = await kubectl.asJson<KubernetesCollection<KubernetesResource>>(`get ${resource} -o json`);
if (failed(rsrcs)) {
vscode.window.showErrorMessage(rsrcs.error[0]);
return [];
}
return rsrcs.result.items.map((item) => {
return {
metadata: item.metadata,
kind: resource
};
});
}
export async function getNamespaces(kubectl: Kubectl): Promise<NamespaceInfo[]> {
const ns = await kubectl.asJson<KubernetesCollection<Namespace>>("get namespaces -o json");
if (failed(ns)) {
vscode.window.showErrorMessage(ns.error[0]);
return [];
}
const currentNS = await currentNamespace(kubectl);
return ns.result.items.map((item) => {
return {
name: item.metadata.name,
active: item.metadata.name === currentNS
};
});
}
export async function getResourceWithSelector(resource: string, kubectl: Kubectl): Promise<HasSelector[]> {
const currentNS = await currentNamespace(kubectl);
const shellResult = await kubectl.asJson<KubernetesCollection<any>>(`get ${resource} -o json --namespace=${currentNS}`);
if (failed(shellResult)) {
vscode.window.showErrorMessage(shellResult.error[0]);
return [];
}
return shellResult.result.items.map((item) => {
return {
name: item.metadata.name,
selector: item.spec.selector
};
});
}
export async function getPods(kubectl: Kubectl, selector: any, namespace: string = null): Promise<PodInfo[]> {
const ns = namespace || await currentNamespace(kubectl);
let nsFlag = `--namespace=${ns}`;
if (ns === 'all') {
nsFlag = '--all-namespaces';
}
const labels = [];
let matchLabelObj = selector;
if (selector && selector.matchLabels) {
matchLabelObj = selector.matchLabels;
}
if (matchLabelObj) {
Object.keys(matchLabelObj).forEach((key) => {
labels.push(`${key}=${matchLabelObj[key]}`);
});
}
let labelStr = "";
if (labels.length > 0) {
labelStr = "--selector=" + labels.join(",");
}
const pods = await kubectl.fromLines(`get pods -o wide ${nsFlag} ${labelStr}`);
if (failed(pods)) {
vscode.window.showErrorMessage(pods.error[0]);
return [];
}
return pods.result.map((item) => {
return {
name: item.name,
namespace: item.namespace || ns,
nodeName: item.node,
status: item.status,
};
});
}
export async function currentNamespace(kubectl: Kubectl): Promise<string> {
const kubectlConfig = await getKubeconfig(kubectl);
if (!kubectlConfig) {
return "";
}
const ctxName = kubectlConfig["current-context"];
const currentContext = kubectlConfig.contexts.find((ctx) => ctx.name === ctxName);
if (!currentContext) {
return "";
}
return currentContext.context.namespace || "default";
}
export async function switchNamespace(kubectl: Kubectl, namespace: string): Promise<boolean> {
const shellResult = await kubectl.invokeAsync("config current-context");
if (shellResult.code !== 0) {
kubeChannel.showOutput(`Failed. Cannot get the current context: ${shellResult.stderr}`, `Switch namespace ${namespace}`);
vscode.window.showErrorMessage("Switch namespace failed. See Output window for more details.");
return false;
}
const updateResult = await kubectl.invokeAsyncWithProgress(`config set-context ${shellResult.stdout.trim()} --namespace="${namespace}"`,
"Switching namespace...");
if (updateResult.code !== 0) {
kubeChannel.showOutput(`Failed to switch the namespace: ${shellResult.stderr}`, `Switch namespace ${namespace}`);
vscode.window.showErrorMessage("Switch namespace failed. See Output window for more details.");
return false;
}
return true;
}
/**
* Run the specified image in the kubernetes cluster.
*
* @param kubectl the kubectl client.
* @param deploymentName the deployment name.
* @param image the docker image.
* @param exposedPorts the exposed ports.
* @param env the additional environment variables when running the docker container.
* @return the deployment name.
*/
export async function runAsDeployment(kubectl: Kubectl, deploymentName: string, image: string, exposedPorts: number[], env: any): Promise<string> {
const imageName = image.split(":")[0];
const imagePrefix = imageName.substring(0, imageName.lastIndexOf("/")+1);
if (!deploymentName) {
const baseName = imageName.substring(imageName.lastIndexOf("/")+1);
deploymentName = `${baseName}-${Date.now()}`;
}
const runCmd = [
"run",
deploymentName,
`--image=${image}`,
imagePrefix ? "" : "--image-pull-policy=Never",
...exposedPorts.map((port) => `--port=${port}`),
...Object.keys(env || {}).map((key) => `--env="${key}=${env[key]}"`)
];
const runResult = await kubectl.invokeAsync(runCmd.join(" "));
if (runResult.code !== 0) {
throw new Error(`Failed to run the image "${image}" on Kubernetes: ${runResult.stderr}`);
}
return deploymentName;
}
/**
* Query the pod list for the specified label.
*
* @param kubectl the kubectl client.
* @param labelQuery the query label.
* @return the pod list.
*/
export async function findPodsByLabel(kubectl: Kubectl, labelQuery: string): Promise<KubernetesCollection<Pod>> {
const getResult = await kubectl.asJson<KubernetesCollection<Pod>>(`get pods -o json -l ${labelQuery}`);
if (failed(getResult)) {
throw new Error('Kubectl command failed: ' + getResult.error[0]);
}
return getResult.result;
}
/**
* Wait and block until the specified pod's status becomes running.
*
* @param kubectl the kubectl client.
* @param podName the pod name.
*/
export async function waitForRunningPod(kubectl: Kubectl, podName: string): Promise<void> {
while (true) {
const shellResult = await kubectl.invokeAsync(`get pod/${podName} --no-headers`);
if (shellResult.code !== 0) {
throw new Error(`Failed to get pod status: ${shellResult.stderr}`);
}
const status = shellResult.stdout.split(/\s+/)[2];
kubeChannel.showOutput(`pod/${podName} status: ${status}`);
if (status === "Running") {
return;
} else if (!isTransientPodState(status)) {
const logsResult = await kubectl.invokeAsync(`logs pod/${podName}`);
kubeChannel.showOutput(`Failed to start the pod "${podName}". Its status is "${status}".
Pod logs:\n${logsResult.code === 0 ? logsResult.stdout : logsResult.stderr}`);
throw new Error(`Failed to start the pod "${podName}". Its status is "${status}".`);
}
await sleep(1000);
}
}
function isTransientPodState(status: string): boolean {
return status === "ContainerCreating" || status === "Pending" || status === "Succeeded";
}
/**
* Get the specified resource information.
*
* @param kubectl the kubectl client.
* @param resourceId the resource id.
* @return the result as a json object, or undefined if errors happen.
*/
export async function getResourceAsJson<T extends KubernetesResource | KubernetesCollection<KubernetesResource>>(kubectl: Kubectl, resourceId: string, resourceNamespace?: string): Promise<T | undefined> {
const nsarg = resourceNamespace ? `--namespace ${resourceNamespace}` : '';
const shellResult = await kubectl.asJson<T>(`get ${resourceId} ${nsarg} -o json`);
if (failed(shellResult)) {
vscode.window.showErrorMessage(shellResult.error[0]);
return undefined;
}
return shellResult.result;
}