paiTrainingService.ts 23.7 KB
Newer Older
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

/**
 * Copyright (c) Microsoft Corporation
 * All rights reserved.
 *
 * MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

'use strict'

import * as component from '../../common/component';
import * as cpp from 'child-process-promise';
import * as fs from 'fs';
import * as path from 'path';
import * as request from 'request';

29
import { CONTAINER_INSTALL_NNI_SHELL_FORMAT } from '../common/containerJobData';
30
31
import { Deferred } from 'ts-deferred';
import { EventEmitter } from 'events';
32
import { getExperimentId, getInitTrialSequenceId } from '../../common/experimentStartupInfo';
33
import { HDFSClientUtility } from './hdfsClientUtility';
34
35
36
37
38
import { MethodNotImplementedError } from '../../common/errors';
import { getLogger, Logger } from '../../common/log';
import { TrialConfigMetadataKey } from '../common/trialConfigMetadataKey';
import {
    JobApplicationForm, TrainingService, TrialJobApplicationForm,
39
    TrialJobDetail, TrialJobMetric, NNIManagerIpConfig
40
} from '../../common/trainingService';
41
import { delay, generateParamFileName, 
42
    getExperimentRootDir, getIPV4Address, uniqueString, getVersion } from '../../common/utils';
43
import { PAIJobRestServer } from './paiJobRestServer'
44
import { PAITrialJobDetail, PAI_TRIAL_COMMAND_FORMAT, PAI_OUTPUT_DIR_FORMAT, PAI_LOG_PATH_FORMAT } from './paiData';
45
46
47
import { PAIJobInfoCollector } from './paiJobInfoCollector';
import { String } from 'typescript-string-operations';
import { NNIPAITrialConfig, PAIClusterConfig, PAIJobConfig, PAITaskRole } from './paiConfig';
48
import { validateCodeDir } from '../common/util';
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

var WebHDFS = require('webhdfs');

/**
 * Training Service implementation for OpenPAI (Open Platform for AI)
 * Refer https://github.com/Microsoft/pai for more info about OpenPAI
 */
@component.Singleton
class PAITrainingService implements TrainingService {
    private readonly log!: Logger;
    private readonly metricsEmitter: EventEmitter;
    private readonly trialJobsMap: Map<string, PAITrialJobDetail>;
    private readonly expRootDir: string;
    private paiTrialConfig: NNIPAITrialConfig | undefined;
    private paiClusterConfig?: PAIClusterConfig;
    private stopping: boolean = false;
    private hdfsClient: any;
    private paiToken? : string;
67
68
    private paiTokenUpdateTime?: number;
    private paiTokenUpdateInterval: number;
69
70
71
    private experimentId! : string;
    private readonly paiJobCollector : PAIJobInfoCollector;
    private readonly hdfsDirPattern: string;
fishyds's avatar
fishyds committed
72
73
    private hdfsBaseDir: string | undefined;
    private hdfsOutputHost: string | undefined;
74
    private nextTrialSequenceId: number;
75
    private paiRestServerPort?: number;
76
    private nniManagerIpConfig?: NNIManagerIpConfig;
77
    private copyExpCodeDirPromise?: Promise<void>;
78
    private versionCheck: boolean = true;
SparkSnail's avatar
SparkSnail committed
79
    private logCollection: string;
80
81
82
83
84
85
86
87
88
89

    constructor() {
        this.log = getLogger();
        this.metricsEmitter = new EventEmitter();
        this.trialJobsMap = new Map<string, PAITrialJobDetail>();
        // Root dir on HDFS
        this.expRootDir = path.join('/nni', 'experiments', getExperimentId());
        this.experimentId = getExperimentId();      
        this.paiJobCollector = new PAIJobInfoCollector(this.trialJobsMap);
        this.hdfsDirPattern = 'hdfs://(?<host>([0-9]{1,3}.){3}[0-9]{1,3})(:[0-9]{2,5})?(?<baseDir>/.*)?';
90
        this.nextTrialSequenceId = -1;
91
        this.paiTokenUpdateInterval = 7200000; //2hours
SparkSnail's avatar
SparkSnail committed
92
        this.logCollection = 'none';
chicm-ms's avatar
chicm-ms committed
93
        this.log.info('Construct OpenPAI training service.');
94
95
96
    }

    public async run(): Promise<void> {
chicm-ms's avatar
chicm-ms committed
97
        this.log.info('Run PAI training service.');
98
99
        const restServer: PAIJobRestServer = component.get(PAIJobRestServer);
        await restServer.start();
100
        restServer.setEnableVersionCheck = this.versionCheck;
101
102
        this.log.info(`PAI Training service rest server listening on: ${restServer.endPoint}`);
        while (!this.stopping) {
103
            await this.updatePaiToken();
104
            await this.paiJobCollector.retrieveTrialStatus(this.paiToken, this.paiClusterConfig);
105
106
107
108
            if (restServer.getErrorMessage) {
                throw new Error(restServer.getErrorMessage)
                this.stopping = true;
            }
109
110
            await delay(3000);
        }
chicm-ms's avatar
chicm-ms committed
111
        this.log.info('PAI training service exit.');
112
113
114
115
116
    }

    public async listTrialJobs(): Promise<TrialJobDetail[]> {
        const jobs: TrialJobDetail[] = [];
        
117
        for (const [key, value] of this.trialJobsMap) { 
118
119
120
            if (value.form.jobType === 'TRIAL') {
                jobs.push(await this.getTrialJob(key));
            }
121
        };
122
123
124
125

        return Promise.resolve(jobs);
    }

126
    public async getTrialJob(trialJobId: string): Promise<TrialJobDetail> {
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
        if(!this.paiClusterConfig) {
            throw new Error('PAI Cluster config is not initialized');
        }

        const paiTrialJob: PAITrialJobDetail | undefined = this.trialJobsMap.get(trialJobId);

        if (!paiTrialJob) {
            return Promise.reject(`trial job ${trialJobId} not found`)
        }        

        return Promise.resolve(paiTrialJob);
    }

    public addTrialJobMetricListener(listener: (metric: TrialJobMetric) => void) {
        this.metricsEmitter.on('metric', listener);
    }

    public removeTrialJobMetricListener(listener: (metric: TrialJobMetric) => void) {
        this.metricsEmitter.off('metric', listener);
    }

    public async submitTrialJob(form: JobApplicationForm): Promise<TrialJobDetail> {
        const deferred : Deferred<PAITrialJobDetail> = new Deferred<PAITrialJobDetail>();
        if(!this.paiClusterConfig) {
            throw new Error('PAI Cluster config is not initialized');
        }
        if (!this.paiTrialConfig) {
            throw new Error('trial config is not initialized');
        }
        if (!this.paiToken) {
            throw new Error('PAI token is not initialized');
        }
fishyds's avatar
fishyds committed
159
        
160
        if(!this.hdfsBaseDir) {
fishyds's avatar
fishyds committed
161
162
163
            throw new Error('hdfsBaseDir is not initialized');
        }

164
        if(!this.hdfsOutputHost) {
fishyds's avatar
fishyds committed
165
166
            throw new Error('hdfsOutputHost is not initialized');
        }
167

168
169
        if(!this.paiRestServerPort) {
            const restServer: PAIJobRestServer = component.get(PAIJobRestServer);
170
            this.paiRestServerPort = restServer.clusterRestServerPort;
171
172
        }

173
174
        this.log.info(`submitTrialJob: form: ${JSON.stringify(form)}`);

175
176
177
178
179
        // Make sure experiment code files is copied from local to HDFS
        if(this.copyExpCodeDirPromise) {
            await this.copyExpCodeDirPromise;
        }

180
        const trialJobId: string = uniqueString(5);
181
        const trialSequenceId: number = this.generateSequenceId();
182
183
184
185
186
        //TODO: use HDFS working folder instead
        const trialWorkingFolder: string = path.join(this.expRootDir, 'trials', trialJobId);
        
        const trialLocalTempFolder: string = path.join(getExperimentRootDir(), 'trials-local', trialJobId);
        //create tmp trial working folder locally.
187
        await cpp.exec(`mkdir -p ${trialLocalTempFolder}`);
fishyds's avatar
fishyds committed
188

189
        const runScriptContent : string = CONTAINER_INSTALL_NNI_SHELL_FORMAT;
fishyds's avatar
fishyds committed
190
191
        // Write NNI installation file to local tmp files
        await fs.promises.writeFile(path.join(trialLocalTempFolder, 'install_nni.sh'), runScriptContent, { encoding: 'utf8' });
192

193
194
195
        // Write file content ( parameter.cfg ) to local tmp folders
        const trialForm : TrialJobApplicationForm = (<TrialJobApplicationForm>form)
        if(trialForm) {
196
197
            await fs.promises.writeFile(path.join(trialLocalTempFolder, generateParamFileName(trialForm.hyperParameters)), 
                            trialForm.hyperParameters.value, { encoding: 'utf8' });
198
199
200
        }
        
        // Step 1. Prepare PAI job configuration
201
202
        const paiJobName: string = `nni_exp_${this.experimentId}_trial_${trialJobId}`;
        const hdfsCodeDir: string = HDFSClientUtility.getHdfsTrialWorkDir(this.paiClusterConfig.userName, trialJobId);
fishyds's avatar
fishyds committed
203
204
        
        const hdfsOutputDir : string = path.join(this.hdfsBaseDir, this.experimentId, trialJobId);
205
206
        const hdfsLogPath : string = String.Format(
            PAI_LOG_PATH_FORMAT,
fishyds's avatar
fishyds committed
207
            this.hdfsOutputHost,
208
209
210
211
212
213
214
215
            hdfsOutputDir);

        const trialJobDetail: PAITrialJobDetail = new PAITrialJobDetail(
            trialJobId,
            'WAITING',
            paiJobName,            
            Date.now(),
            trialWorkingFolder,
216
217
            form,
            trialSequenceId,
218
219
            hdfsLogPath);
        this.trialJobsMap.set(trialJobId, trialJobDetail);
220
        const nniManagerIp = this.nniManagerIpConfig?this.nniManagerIpConfig.nniManagerIp:getIPV4Address();
221
        const version = this.versionCheck? await getVersion(): '';
222
223
224
        const nniPaiTrialCommand : string = String.Format(
            PAI_TRIAL_COMMAND_FORMAT,
            // PAI will copy job's codeDir into /root directory
225
226
            `$PWD/${trialJobId}`,
            `$PWD/${trialJobId}/nnioutput`,
227
228
            trialJobId,
            this.experimentId,
229
            trialSequenceId,
230
            this.paiTrialConfig.command, 
231
            nniManagerIp,
232
            this.paiRestServerPort,
233
            hdfsOutputDir,
fishyds's avatar
fishyds committed
234
            this.hdfsOutputHost,
235
            this.paiClusterConfig.userName, 
236
            HDFSClientUtility.getHdfsExpCodeDir(this.paiClusterConfig.userName),
SparkSnail's avatar
SparkSnail committed
237
238
            version,
            this.logCollection
239
240
241
242
243
244
245
246
247
248
249
250
251
        ).replace(/\r\n|\n|\r/gm, '');

        console.log(`nniPAItrial command is ${nniPaiTrialCommand.trim()}`);
        const paiTaskRoles : PAITaskRole[] = [new PAITaskRole('nni_trail_' + trialJobId, 
                                    // Task role number
                                    1, 
                                    // Task CPU number
                                    this.paiTrialConfig.cpuNum, 
                                    // Task memory
                                    this.paiTrialConfig.memoryMB, 
                                    // Task GPU number
                                    this.paiTrialConfig.gpuNum, 
                                    // Task command
252
253
254
                                    nniPaiTrialCommand,
                                    // Task shared memory
                                    this.paiTrialConfig.shmMB)];
255
256
257
258
259
260
261
262
263
264
265
266
267

        const paiJobConfig : PAIJobConfig = new PAIJobConfig(
                                    // Job name
                                    paiJobName, 
                                    // Docker image
                                    this.paiTrialConfig.image, 
                                    // dataDir
                                    this.paiTrialConfig.dataDir, 
                                    // outputDir
                                    this.paiTrialConfig.outputDir, 
                                    // codeDir
                                    `$PAI_DEFAULT_FS_URI${hdfsCodeDir}`, 
                                    // PAI Task roles
268
269
270
                                    paiTaskRoles, 
                                    // Add Virutal Cluster 
                                    this.paiTrialConfig.virtualCluster === undefined ? 'default' : this.paiTrialConfig.virtualCluster.toString());
271
272
273
274
275
276
277
278
279
280
281
282

        // Step 2. Upload code files in codeDir onto HDFS
        try {
            await HDFSClientUtility.copyDirectoryToHdfs(trialLocalTempFolder, hdfsCodeDir, this.hdfsClient);
        } catch (error) {
            this.log.error(`PAI Training service: copy ${this.paiTrialConfig.codeDir} to HDFS ${hdfsCodeDir} failed, error is ${error}`);
            throw new Error(error.message);
        }

        // Step 3. Submit PAI job via Rest call
        // Refer https://github.com/Microsoft/pai/blob/master/docs/rest-server/API.md for more detail about PAI Rest API
        const submitJobRequest: request.Options = {
283
            uri: `http://${this.paiClusterConfig.host}/rest-server/api/v1/user/${this.paiClusterConfig.userName}/jobs`,
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
            method: 'POST',
            json: true,
            body: paiJobConfig,
            headers: {
                "Content-Type": "application/json",
                "Authorization": 'Bearer ' + this.paiToken
            }
        };
        request(submitJobRequest, (error: Error, response: request.Response, body: any) => {
            if (error || response.statusCode >= 400) {
                this.log.error(`PAI Training service: Submit trial ${trialJobId} to PAI Cluster failed!`);
                trialJobDetail.status = 'FAILED';
                deferred.reject(error ? error.message : 'Submit trial failed, http code: ' + response.statusCode);                
            } else {
                trialJobDetail.submitTime = Date.now();
                deferred.resolve(trialJobDetail);
            }
        });

        return deferred.promise;
    }

    public updateTrialJob(trialJobId: string, form: JobApplicationForm): Promise<TrialJobDetail> {
        throw new MethodNotImplementedError();
    }

    public get isMultiPhaseJobSupported(): boolean {
        return false;
    }

QuanluZhang's avatar
QuanluZhang committed
314
    public cancelTrialJob(trialJobId: string, isEarlyStopped: boolean = false): Promise<void> {
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
        const trialJobDetail : PAITrialJobDetail | undefined =  this.trialJobsMap.get(trialJobId);
        const deferred : Deferred<void> = new Deferred<void>();
        if(!trialJobDetail) {
            this.log.error(`cancelTrialJob: trial job id ${trialJobId} not found`);
            return Promise.reject();
        }

        if(!this.paiClusterConfig) {
            throw new Error('PAI Cluster config is not initialized');
        }        
        if (!this.paiToken) {
            throw new Error('PAI token is not initialized');
        }

        const stopJobRequest: request.Options = {
330
            uri: `http://${this.paiClusterConfig.host}/rest-server/api/v1/user/${this.paiClusterConfig.userName}/jobs/${trialJobDetail.paiJobName}/executionType`,
331
332
333
334
335
336
337
338
            method: 'PUT',
            json: true,
            body: {'value' : 'STOP'},
            headers: {
                "Content-Type": "application/json",
                "Authorization": 'Bearer ' + this.paiToken
            }
        };
339
340
341
342

        // Set trialjobDetail's early stopped field, to mark the job's cancellation source
        trialJobDetail.isEarlyStopped = isEarlyStopped;

343
344
345
346
347
348
349
350
351
352
353
354
        request(stopJobRequest, (error: Error, response: request.Response, body: any) => {
            if (error || response.statusCode >= 400) {
                this.log.error(`PAI Training service: stop trial ${trialJobId} to PAI Cluster failed!`);
                deferred.reject(error ? error.message : 'Stop trial failed, http code: ' + response.statusCode);                
            } else {
                deferred.resolve();
            }
        });

        return deferred.promise; 
    }

fishyds's avatar
fishyds committed
355
    public async setClusterMetadata(key: string, value: string): Promise<void> {
356
357
358
        const deferred : Deferred<void> = new Deferred<void>();

        switch (key) {
359
360
361
362
363
            case TrialConfigMetadataKey.NNI_MANAGER_IP:
                this.nniManagerIpConfig = <NNIManagerIpConfig>JSON.parse(value);
                deferred.resolve();
                break;

364
365
366
367
368
369
            case TrialConfigMetadataKey.PAI_CLUSTER_CONFIG:
                //TODO: try catch exception when setting up HDFS client and get PAI token
                this.paiClusterConfig = <PAIClusterConfig>JSON.parse(value);
                
                this.hdfsClient = WebHDFS.createClient({
                    user: this.paiClusterConfig.userName,
370
371
                    // Refer PAI document for Pylon mapping https://github.com/Microsoft/pai/tree/master/docs/pylon
                    port: 80,
372
                    path: '/webhdfs/api/v1',
373
374
375
376
                    host: this.paiClusterConfig.host
                });

                // Get PAI authentication token
377
                await this.updatePaiToken();
378
                deferred.resolve();
379
                break;
380

381
382
383
            case TrialConfigMetadataKey.TRIAL_CONFIG:
                if (!this.paiClusterConfig){
                    this.log.error('pai cluster config is not initialized');
fishyds's avatar
fishyds committed
384
                    deferred.reject(new Error('pai cluster config is not initialized'));
385
386
387
388
389
390
391
392
393
394
                    break;
                }
                this.paiTrialConfig = <NNIPAITrialConfig>JSON.parse(value);
                //paiTrialConfig.outputDir could be null if it is not set in nnictl
                if(this.paiTrialConfig.outputDir === undefined || this.paiTrialConfig.outputDir === null){
                    this.paiTrialConfig.outputDir = String.Format(
                        PAI_OUTPUT_DIR_FORMAT,
                        this.paiClusterConfig.host
                    ).replace(/\r\n|\n|\r/gm, '');
                }
395

396
397
398
399
400
401
402
403
404
                // Validate to make sure codeDir doesn't have too many files
                try {
                    await validateCodeDir(this.paiTrialConfig.codeDir);
                } catch(error) {
                    this.log.error(error);
                    deferred.reject(new Error(error));
                    break;
                }

fishyds's avatar
fishyds committed
405
406
407
408
409
410
411
412
413
414
415
                const hdfsDirContent = this.paiTrialConfig.outputDir.match(this.hdfsDirPattern);

                if(hdfsDirContent === null) {
                    throw new Error('Trial outputDir format Error');
                }
                const groups = hdfsDirContent.groups;
                if(groups === undefined) {
                    throw new Error('Trial outputDir format Error');
                }
        
                this.hdfsOutputHost = groups['host'];
416
                //TODO: choose to use /${username} as baseDir
fishyds's avatar
fishyds committed
417
418
419
420
421
                this.hdfsBaseDir = groups['baseDir'];
                if(this.hdfsBaseDir === undefined) {
                    this.hdfsBaseDir = "/";
                }
                
422
423
424
425
426
427
428
429
430
431
                let dataOutputHdfsClient; 
                if (this.paiClusterConfig.host === this.hdfsOutputHost && this.hdfsClient) {
                    dataOutputHdfsClient = this.hdfsClient
                } else {
                    dataOutputHdfsClient = WebHDFS.createClient({
                        user: this.paiClusterConfig.userName,
                        port: 50070,
                        host: this.hdfsOutputHost
                    });
                }
fishyds's avatar
fishyds committed
432
433

                try {
434
                    const exist : boolean = await HDFSClientUtility.pathExists("/", dataOutputHdfsClient);
fishyds's avatar
fishyds committed
435
436
437
438
439
440
                    if(!exist) {
                        deferred.reject(new Error(`Please check hdfsOutputDir host!`));
                    }
                } catch(error) {
                    deferred.reject(new Error(`HDFS encounters problem, error is ${error}. Please check hdfsOutputDir host!`));
                }
441
442
443
444
445
                
                // Copy experiment files from local folder to HDFS
                this.copyExpCodeDirPromise = HDFSClientUtility.copyDirectoryToHdfs(this.paiTrialConfig.codeDir, 
                    HDFSClientUtility.getHdfsExpCodeDir(this.paiClusterConfig.userName),
                    this.hdfsClient);
fishyds's avatar
fishyds committed
446

447
448
                deferred.resolve();
                break;
449
450
451
            case TrialConfigMetadataKey.VERSION_CHECK:
                this.versionCheck = (value === 'true' || value === 'True');
                break;
SparkSnail's avatar
SparkSnail committed
452
453
454
            case TrialConfigMetadataKey.LOG_COLLECTION:
                this.logCollection = value;
                break;
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
            default:
                //Reject for unknown keys
                throw new Error(`Uknown key: ${key}`);
        }

        return deferred.promise; 
    }

    public getClusterMetadata(key: string): Promise<string> {
        const deferred : Deferred<string> = new Deferred<string>();

        deferred.resolve();
        return deferred.promise; 
    }

    public async cleanUp(): Promise<void> {
chicm-ms's avatar
chicm-ms committed
471
        this.log.info('Stopping PAI training service...');
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
        this.stopping = true;

        const deferred : Deferred<void> = new Deferred<void>();
        const restServer: PAIJobRestServer = component.get(PAIJobRestServer);
        try {
            await restServer.stop();
            deferred.resolve();
            this.log.info('PAI Training service rest server stopped successfully.');
        } catch (error) {
            this.log.error(`PAI Training service rest server stopped failed, error: ${error.message}`);    
            deferred.reject(error);
        }

        return deferred.promise; 
    }

    public get MetricsEmitter() : EventEmitter {
        return this.metricsEmitter;
    }
491
492

    private generateSequenceId(): number {
493
494
        if (this.nextTrialSequenceId === -1) {
            this.nextTrialSequenceId = getInitTrialSequenceId();
495
496
        }

497
        return this.nextTrialSequenceId++;
498
    }
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
    
    /**
     * Update pai token by the interval time or initialize the pai token
     */
    private async updatePaiToken(): Promise<void> {
        const deferred : Deferred<void> = new Deferred<void>();
        
        let currentTime: number = new Date().getTime();
        //If pai token initialized and not reach the interval time, do not update
        if(this.paiTokenUpdateTime && (currentTime - this.paiTokenUpdateTime) < this.paiTokenUpdateInterval){
            return Promise.resolve();
        }
     
        if(!this.paiClusterConfig){
            const paiClusterConfigError = `pai cluster config not initialized!`
            this.log.error(`${paiClusterConfigError}`);
            throw Error(`${paiClusterConfigError}`)
        }

        const authentication_req: request.Options = {
            uri: `http://${this.paiClusterConfig.host}/rest-server/api/v1/token`,
            method: 'POST',
            json: true,
            body: {
                username: this.paiClusterConfig.userName,
                password: this.paiClusterConfig.passWord
            }
        };

        request(authentication_req, (error: Error, response: request.Response, body: any) => {
            if (error) {
                this.log.error(`Get PAI token failed: ${error.message}`);
                deferred.reject(new Error(`Get PAI token failed: ${error.message}`));
            } else {
                if(response.statusCode !== 200){
                    this.log.error(`Get PAI token failed: get PAI Rest return code ${response.statusCode}`);
535
                    deferred.reject(new Error(`Get PAI token failed: ${response.body}, please check paiConfig username or password`));
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
                }
                this.paiToken = body.token;
                this.paiTokenUpdateTime = new Date().getTime();
                deferred.resolve();
            }
        });
        
        let timeoutId: NodeJS.Timer;
        const timeoutDelay: Promise<void> = new Promise<void>((resolve: Function, reject: Function): void => {
            // Set timeout and reject the promise once reach timeout (5 seconds)
            timeoutId = setTimeout(
                () => reject(new Error('Get PAI token timeout. Please check your PAI cluster.')),
                5000);
        });

        return Promise.race([timeoutDelay, deferred.promise]).finally(() => clearTimeout(timeoutId));
    }
553
554
}

QuanluZhang's avatar
QuanluZhang committed
555
export { PAITrainingService }