|
3 | 3 | * Licensed under the MIT License. See LICENSE file in the project root for license information. |
4 | 4 | *-----------------------------------------------------------------------------------------------*/ |
5 | 5 |
|
| 6 | +import * as fs from 'fs'; |
| 7 | +import * as path from 'path'; |
6 | 8 | import { QuickPickItem } from 'vscode'; |
7 | | -import { KubeConfig } from '@kubernetes/client-node'; |
| 9 | +import { KubeConfig, findHomeDir, loadYaml } from '@kubernetes/client-node'; |
8 | 10 | import { User, Cluster } from '@kubernetes/client-node/dist/config_types'; |
9 | 11 |
|
| 12 | +function fileExists(file: string): boolean { |
| 13 | + try { |
| 14 | + fs.accessSync(file); |
| 15 | + return true; |
| 16 | + } catch ( _ ) { |
| 17 | + return false; |
| 18 | + } |
| 19 | +} |
| 20 | + |
10 | 21 | export class KubeConfigUtils extends KubeConfig { |
11 | 22 | constructor() { |
12 | 23 | super(); |
13 | 24 | this.loadFromDefault(); |
| 25 | + // k8s nodejs-client ignores all unknown properties, |
| 26 | + // so cluster object's proxy-url attribute is not present |
| 27 | + // after k8s config loaded |
| 28 | + } |
| 29 | + |
| 30 | + findHomeDir() { |
| 31 | + return findHomeDir(); |
| 32 | + } |
| 33 | + |
| 34 | + getProxy(contextName: string): string | undefined { |
| 35 | + if (process.env.KUBECONFIG?.[1]) { |
| 36 | + const cFiles = process.env.KUBECONFIG.split(path.delimiter).filter(file => file); |
| 37 | + //const yaml = |
| 38 | + for (let i=0; i < cFiles.length; i++) { |
| 39 | + const proxyUrl = this.getClusterProxyFromFile(cFiles[i], contextName); |
| 40 | + if (proxyUrl) return proxyUrl; |
| 41 | + } |
| 42 | + return; |
| 43 | + } |
| 44 | + const home = this.findHomeDir(); |
| 45 | + if (home) { |
| 46 | + const config = path.join(home, '.kube', 'config'); |
| 47 | + if (fileExists(config)) { |
| 48 | + return this.getClusterProxyFromFile(config, contextName); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + getClusterProxyFromFile(file: string, contextName: string): string { |
| 54 | + const fileContent = fs.readFileSync(file, 'utf8'); |
| 55 | + const yaml: any = loadYaml(fileContent); |
| 56 | + const contextObj = yaml.contexts.find( |
| 57 | + (context) => context.name === contextName); |
| 58 | + const clusterObj = yaml.clusters.find( |
| 59 | + (cluster) => cluster.name === contextObj?.context?.cluster); |
| 60 | + return clusterObj?.cluster?.['proxy-url']; |
14 | 61 | } |
15 | 62 |
|
16 | 63 | public getServers(): QuickPickItem[] { |
|
0 commit comments