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

'use strict';

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

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * 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();
    }
}

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

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

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

45
46
47
48
49
50
51
52
    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,
53
            responseLen = response.items.length
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
        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>;
86
        const response: any = await this.client.apis.apps.v1.namespaces(this.namespace)
87
            .deployments.post({body: deploymentManifest})
88
89
90
91
92
93
94
95
96
97
98
        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
99
        const response: any = await this.client.apis.apps.v1.namespaces(this.namespace)
100
            .deployment(deploymentName).delete();
101
102
103
104
105
106
107
108
109
110
        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>;
111
        const response: any = await this.client.api.v1.namespaces(this.namespace)
112
            .configmaps.post({body: configMapManifest});
113
114
115
116
117
118
119
120
121
122
123
        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>;
124
        const response: any = await this.client.api.v1.namespaces(this.namespace)
125
            .persistentvolumeclaims.post({body: pvcManifest});
126
127
128
129
130
131
132
133
        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;
    }

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

144
145
146
147
        return result;
    }
}

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

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

    protected abstract get operator(): any;

    public abstract get containerName(): string;

    public get jobKind(): string {
166
        if (this.crdSchema
167
            && this.crdSchema.spec
168
169
170
171
172
173
174
175
176
            && 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 {
177
        if (this.crdSchema
178
            && this.crdSchema.spec
179
180
181
182
183
184
            && this.crdSchema.spec.version) {
            return this.crdSchema.spec.version;
        } else {
            throw new Error('KubeflowOperatorClient: get apiVersion failed, version is undefined in crd schema!');
        }
    }
185

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

195
196
197
198
        return result;
    }

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

209
210
211
        return result;
    }

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

        return result;
    }
}

240
export {KubernetesCRDClient, GeneralK8sClient};