kubernetesApiClient.ts 8.8 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
153
154
    protected crdSchema: any;

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

    protected abstract get operator(): any;

    public abstract get containerName(): string;

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

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

193
194
195
196
        return result;
    }

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

207
208
209
        return result;
    }

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

        return result;
    }
}

238
export {KubernetesCRDClient, GeneralK8sClient};