kubernetesApiClient.ts 8.84 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
3

chicm-ms's avatar
chicm-ms committed
4
// eslint-disable-next-line @typescript-eslint/camelcase
5
import {Client1_10, config} from 'kubernetes-client';
6
import {getLogger, Logger} from 'common/log';
7

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * This function uses the environment variable
 * 'KUBERNETES_SERVICE_HOST' to determine whether
 * the code is running from within a kubernetes container.
 * If it is, it returns the in-cluster config
 * instead of the kubeconfig.
 */
function getKubernetesConfig(): any {
    if ('KUBERNETES_SERVICE_HOST' in process.env) {
        return config.getInCluster();
    } else {
        return config.fromKubeconfig();
    }
}

23
/**
24
 * Generic Kubernetes client, target version >= 1.9
25
26
27
 */
class GeneralK8sClient {
    protected readonly client: any;
liuzhe-lz's avatar
liuzhe-lz committed
28
    protected readonly log: Logger = getLogger('GeneralK8sClient');
29
    protected namespace: string = 'default';
30
31

    constructor() {
32
        this.client = new Client1_10({config: getKubernetesConfig(), version: '1.9'});
33
34
35
        this.client.loadSpec();
    }

36
37
38
    public set setNamespace(namespace: string) {
        this.namespace = namespace;
    }
39
40
41
    public get getNamespace(): string {
        return this.namespace;
    }
42

43
44
45
46
47
48
49
50
    private matchStorageClass(response: any): string {
        const adlSupportedProvisioners: RegExp[] = [
            new RegExp("microk8s.io/hostpath"),
            new RegExp(".*cephfs.csi.ceph.com"),
            new RegExp(".*azure.*"),
            new RegExp("\\b" + "efs" + "\\b")
        ]
        const templateLen = adlSupportedProvisioners.length,
51
            responseLen = response.items.length
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
        let i = 0,
            j = 0;
        for (; i < responseLen; i++) {
            const provisioner: string = response.items[i].provisioner
            for (; j < templateLen; j++) {
                if (provisioner.match(adlSupportedProvisioners[j])) {
                    return response.items[i].metadata.name;
                }
            }
        }
        return "Not Found!";
    }

    public async getStorageClass(): Promise<string> {
        let result: Promise<string>;
        const response: any = await this.client.apis["storage.k8s.io"].v1beta1.storageclasses.get()
        const storageClassType: string = this.matchStorageClass(response.body)
        if (response.statusCode && (response.statusCode >= 200 && response.statusCode <= 299)) {
            if (storageClassType != "Not Found!") {
                result = Promise.resolve(storageClassType);
            }
            else {
                result = Promise.reject("No StorageClasses are supported!")
            }
        } else {
            result = Promise.reject(`List storageclasses failed, statusCode is ${response.statusCode}`);
        }
        return result;
    }

    public async createDeployment(deploymentManifest: any): Promise<string> {
        let result: Promise<string>;
84
        const response: any = await this.client.apis.apps.v1.namespaces(this.namespace)
85
            .deployments.post({body: deploymentManifest})
86
87
88
89
90
91
92
93
94
95
96
        if (response.statusCode && (response.statusCode >= 200 && response.statusCode <= 299)) {
            result = Promise.resolve(response.body.metadata.uid);
        } else {
            result = Promise.reject(`Create deployment failed, statusCode is ${response.statusCode}`);
        }
        return result;
    }

    public async deleteDeployment(deploymentName: string): Promise<boolean> {
        let result: Promise<boolean>;
        // TODO: change this hard coded deployment name after demo
97
        const response: any = await this.client.apis.apps.v1.namespaces(this.namespace)
98
            .deployment(deploymentName).delete();
99
100
101
102
103
104
105
106
107
108
        if (response.statusCode && (response.statusCode >= 200 && response.statusCode <= 299)) {
            result = Promise.resolve(true);
        } else {
            result = Promise.reject(`Delete deployment failed, statusCode is ${response.statusCode}`);
        }
        return result;
    }

    public async createConfigMap(configMapManifest: any): Promise<boolean> {
        let result: Promise<boolean>;
109
        const response: any = await this.client.api.v1.namespaces(this.namespace)
110
            .configmaps.post({body: configMapManifest});
111
112
113
114
115
116
117
118
119
120
121
        if (response.statusCode && (response.statusCode >= 200 && response.statusCode <= 299)) {
            result = Promise.resolve(true);
        } else {
            result = Promise.reject(`Create configMap failed, statusCode is ${response.statusCode}`);
        }

        return result;
    }

    public async createPersistentVolumeClaim(pvcManifest: any): Promise<boolean> {
        let result: Promise<boolean>;
122
        const response: any = await this.client.api.v1.namespaces(this.namespace)
123
            .persistentvolumeclaims.post({body: pvcManifest});
124
125
126
127
128
129
130
131
        if (response.statusCode && (response.statusCode >= 200 && response.statusCode <= 299)) {
            result = Promise.resolve(true);
        } else {
            result = Promise.reject(`Create pvc failed, statusCode is ${response.statusCode}`);
        }
        return result;
    }

132
    public async createSecret(secretManifest: any): Promise<boolean> {
133
        let result: Promise<boolean>;
134
        const response: any = await this.client.api.v1.namespaces(this.namespace)
135
            .secrets.post({body: secretManifest});
136
        if (response.statusCode && (response.statusCode >= 200 && response.statusCode <= 299)) {
137
138
139
140
            result = Promise.resolve(true);
        } else {
            result = Promise.reject(`Create secrets failed, statusCode is ${response.statusCode}`);
        }
141

142
143
144
145
        return result;
    }
}

146
147
148
/**
 * Kubernetes CRD client
 */
149
abstract class KubernetesCRDClient {
150
    protected readonly client: any;
liuzhe-lz's avatar
liuzhe-lz committed
151
    protected readonly log: Logger = getLogger('KubernetesCRDClient');
152
    protected crdSchema: any;
J-shang's avatar
J-shang committed
153
    public namespace: string = 'default';
154
155

    constructor() {
156
        this.client = new Client1_10({config: getKubernetesConfig()});
157
158
159
160
161
162
163
164
        this.client.loadSpec();
    }

    protected abstract get operator(): any;

    public abstract get containerName(): string;

    public get jobKind(): string {
165
        if (this.crdSchema
166
            && this.crdSchema.spec
167
168
169
170
171
172
173
174
175
            && this.crdSchema.spec.names
            && this.crdSchema.spec.names.kind) {
            return this.crdSchema.spec.names.kind;
        } else {
            throw new Error('KubeflowOperatorClient: getJobKind failed, kind is undefined in crd schema!');
        }
    }

    public get apiVersion(): string {
176
        if (this.crdSchema
177
            && this.crdSchema.spec
178
179
180
181
182
183
            && this.crdSchema.spec.version) {
            return this.crdSchema.spec.version;
        } else {
            throw new Error('KubeflowOperatorClient: get apiVersion failed, version is undefined in crd schema!');
        }
    }
184

185
    public async createKubernetesJob(jobManifest: any): Promise<boolean> {
186
        let result: Promise<boolean>;
chicm-ms's avatar
chicm-ms committed
187
        const response: any = await this.operator.post({body: jobManifest});
188
        if (response.statusCode && (response.statusCode >= 200 && response.statusCode <= 299)) {
189
190
            result = Promise.resolve(true);
        } else {
191
            result = Promise.reject(`KubernetesApiClient createKubernetesJob failed, statusCode is ${response.statusCode}`);
192
        }
193

194
195
196
197
        return result;
    }

    //TODO : replace any
198
    public async getKubernetesJob(kubeflowJobName: string): Promise<any> {
199
        let result: Promise<any>;
chicm-ms's avatar
chicm-ms committed
200
        const response: any = await this.operator(kubeflowJobName)
201
            .get();
202
        if (response.statusCode && (response.statusCode >= 200 && response.statusCode <= 299)) {
203
204
            result = Promise.resolve(response.body);
        } else {
205
            result = Promise.reject(`KubernetesApiClient getKubernetesJob failed, statusCode is ${response.statusCode}`);
206
        }
207

208
209
210
        return result;
    }

211
    public async deleteKubernetesJob(labels: Map<string, string>): Promise<boolean> {
212
213
        let result: Promise<boolean>;
        // construct match query from labels for deleting tfjob
214
        const matchQuery: string = Array.from(labels.keys())
215
216
            .map((labelKey: string) => `${labelKey}=${labels.get(labelKey)}`)
            .join(',');
217
        try {
chicm-ms's avatar
chicm-ms committed
218
            const deleteResult: any = await this.operator()
219
220
221
222
223
224
                .delete({
                    qs: {
                        labelSelector: matchQuery,
                        propagationPolicy: 'Background'
                    }
                });
225
            if (deleteResult.statusCode && deleteResult.statusCode >= 200 && deleteResult.statusCode <= 299) {
226
227
                result = Promise.resolve(true);
            } else {
228
                result = Promise.reject(
229
                    `KubernetesApiClient, delete labels ${matchQuery} get wrong statusCode ${deleteResult.statusCode}`);
230
            }
231
        } catch (err) {
232
233
234
235
236
237
238
            result = Promise.reject(err);
        }

        return result;
    }
}

239
export {KubernetesCRDClient, GeneralK8sClient};