restHandler.ts 11 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Deshui Yu's avatar
Deshui Yu committed
3
4
5
6
7
8
9
10
11

'use strict';

import { Request, Response, Router } from 'express';
import * as path from 'path';

import * as component from '../common/component';
import { DataStore, MetricDataRecord, TrialJobInfo } from '../common/datastore';
import { NNIError, NNIErrorNames } from '../common/errors';
SparkSnail's avatar
SparkSnail committed
12
import { isNewExperiment, isReadonly } from '../common/experimentStartupInfo';
Deshui Yu's avatar
Deshui Yu committed
13
import { getLogger, Logger } from '../common/log';
chicm-ms's avatar
chicm-ms committed
14
import { ExperimentProfile, Manager, TrialJobStatistics } from '../common/manager';
15
16
import { ValidationSchemas } from './restValidationSchemas';
import { NNIRestServer } from './nniRestServer';
17
import { getVersion } from '../common/utils';
Deshui Yu's avatar
Deshui Yu committed
18

19
20
const expressJoi = require('express-joi-validator');

Deshui Yu's avatar
Deshui Yu committed
21
class NNIRestHandler {
22
    private restServer: NNIRestServer;
Deshui Yu's avatar
Deshui Yu committed
23
24
25
    private nniManager: Manager;
    private log: Logger;

26
    constructor(rs: NNIRestServer) {
Deshui Yu's avatar
Deshui Yu committed
27
28
29
30
31
32
33
34
35
        this.nniManager = component.get(Manager);
        this.restServer = rs;
        this.log = getLogger();
    }

    public createRestHandler(): Router {
        const router: Router = Router();

        router.use((req: Request, res: Response, next) => {
chicm-ms's avatar
chicm-ms committed
36
            this.log.debug(`${req.method}: ${req.url}: body:\n${JSON.stringify(req.body, undefined, 4)}`);
Deshui Yu's avatar
Deshui Yu committed
37
38
39
40
41
42
43
44
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
            res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');

            res.setHeader('Content-Type', 'application/json');
            next();
        });

Gems Guo's avatar
Gems Guo committed
45
        this.version(router);
Deshui Yu's avatar
Deshui Yu committed
46
47
48
        this.checkStatus(router);
        this.getExperimentProfile(router);
        this.updateExperimentProfile(router);
49
        this.importData(router);
Deshui Yu's avatar
Deshui Yu committed
50
51
52
53
54
55
56
57
        this.startExperiment(router);
        this.getTrialJobStatistics(router);
        this.setClusterMetaData(router);
        this.listTrialJobs(router);
        this.getTrialJob(router);
        this.addTrialJob(router);
        this.cancelTrialJob(router);
        this.getMetricData(router);
58
59
        this.getMetricDataByRange(router);
        this.getLatestMetricData(router);
60
        this.exportData(router);
Deshui Yu's avatar
Deshui Yu committed
61

62
63
64
65
66
67
68
69
70
        // Express-joi-validator configuration
        router.use((err: any, req: Request, res: Response, next: any) => {
            if (err.isBoom) {
                this.log.error(err.output.payload);

                return res.status(err.output.statusCode).json(err.output.payload);
            }
        });

Deshui Yu's avatar
Deshui Yu committed
71
72
73
        return router;
    }

chicm-ms's avatar
chicm-ms committed
74
    private handleError(err: Error, res: Response, isFatal: boolean = false, errorCode: number = 500): void {
Deshui Yu's avatar
Deshui Yu committed
75
76
77
        if (err instanceof NNIError && err.name === NNIErrorNames.NOT_FOUND) {
            res.status(404);
        } else {
SparkSnail's avatar
SparkSnail committed
78
            res.status(errorCode);
Deshui Yu's avatar
Deshui Yu committed
79
80
81
82
        }
        res.send({
            error: err.message
        });
83
84

        // If it's a fatal error, exit process
chicm-ms's avatar
chicm-ms committed
85
        if (isFatal) {
86
            this.log.fatal(err);
87
            process.exit(1);
chicm-ms's avatar
chicm-ms committed
88
89
        } else {
            this.log.error(err);
90
        }
Deshui Yu's avatar
Deshui Yu committed
91
92
    }

Gems Guo's avatar
Gems Guo committed
93
94
    private version(router: Router): void {
        router.get('/version', async (req: Request, res: Response) => {
95
96
            const version = await getVersion();
            res.send(version);
Gems Guo's avatar
Gems Guo committed
97
98
99
        });
    }

Deshui Yu's avatar
Deshui Yu committed
100
101
102
103
104
    // TODO add validators for request params, query, body
    private checkStatus(router: Router): void {
        router.get('/check-status', (req: Request, res: Response) => {
            const ds: DataStore = component.get<DataStore>(DataStore);
            ds.init().then(() => {
105
                res.send(this.nniManager.getStatus());
Deshui Yu's avatar
Deshui Yu committed
106
            }).catch(async (err: Error) => {
chicm-ms's avatar
chicm-ms committed
107
                this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
108
                this.log.error(err.message);
chicm-ms's avatar
chicm-ms committed
109
                this.log.error(`Datastore initialize failed, stopping rest server...`);
Deshui Yu's avatar
Deshui Yu committed
110
111
112
113
114
115
116
117
118
119
                await this.restServer.stop();
            });
        });
    }

    private getExperimentProfile(router: Router): void {
        router.get('/experiment', (req: Request, res: Response) => {
            this.nniManager.getExperimentProfile().then((profile: ExperimentProfile) => {
                res.send(profile);
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
120
                this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
121
122
123
124
125
            });
        });
    }

    private updateExperimentProfile(router: Router): void {
126
        router.put('/experiment', expressJoi(ValidationSchemas.UPDATEEXPERIMENT), (req: Request, res: Response) => {
Deshui Yu's avatar
Deshui Yu committed
127
128
129
            this.nniManager.updateExperimentProfile(req.body, req.query.update_type).then(() => {
                res.send();
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
130
                this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
131
132
133
            });
        });
    }
134

135
136
137
138
139
    private importData(router: Router): void {
        router.post('/experiment/import-data', (req: Request, res: Response) => {
            this.nniManager.importData(JSON.stringify(req.body)).then(() => {
                res.send();
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
140
                this.handleError(err, res);
141
142
143
            });
        });
    }
Deshui Yu's avatar
Deshui Yu committed
144
145

    private startExperiment(router: Router): void {
146
        router.post('/experiment', expressJoi(ValidationSchemas.STARTEXPERIMENT), (req: Request, res: Response) => {
Deshui Yu's avatar
Deshui Yu committed
147
148
149
            if (isNewExperiment()) {
                this.nniManager.startExperiment(req.body).then((eid: string) => {
                    res.send({
chicm-ms's avatar
chicm-ms committed
150
                        experiment_id: eid // eslint-disable-line @typescript-eslint/camelcase
Deshui Yu's avatar
Deshui Yu committed
151
152
                    });
                }).catch((err: Error) => {
153
                    // Start experiment is a step of initialization, so any exception thrown is a fatal
chicm-ms's avatar
chicm-ms committed
154
                    this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
155
156
                });
            } else {
SparkSnail's avatar
SparkSnail committed
157
                this.nniManager.resumeExperiment(isReadonly()).then(() => {
Deshui Yu's avatar
Deshui Yu committed
158
159
                    res.send();
                }).catch((err: Error) => {
160
                    // Resume experiment is a step of initialization, so any exception thrown is a fatal
chicm-ms's avatar
chicm-ms committed
161
                    this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
162
                });
SparkSnail's avatar
SparkSnail committed
163
            } 
Deshui Yu's avatar
Deshui Yu committed
164
165
166
167
168
169
170
171
        });
    }

    private getTrialJobStatistics(router: Router): void {
        router.get('/job-statistics', (req: Request, res: Response) => {
            this.nniManager.getTrialJobStatistics().then((statistics: TrialJobStatistics[]) => {
                res.send(statistics);
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
172
                this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
173
174
175
176
177
            });
        });
    }

    private setClusterMetaData(router: Router): void {
178
179
180
        router.put(
            '/experiment/cluster-metadata', expressJoi(ValidationSchemas.SETCLUSTERMETADATA),
            async (req: Request, res: Response) => {
SparkSnail's avatar
SparkSnail committed
181
182
183
184
185
186
187
188
189
                const metadata: any = req.body;
                const keys: string[] = Object.keys(metadata);
                try {
                    for (const key of keys) {
                        await this.nniManager.setClusterMetadata(key, JSON.stringify(metadata[key]));
                    }
                    res.send();
                } catch (err) {
                    // setClusterMetata is a step of initialization, so any exception thrown is a fatal
chicm-ms's avatar
chicm-ms committed
190
                    this.handleError(NNIError.FromError(err), res, true);
Deshui Yu's avatar
Deshui Yu committed
191
192
193
194
195
196
197
198
199
200
201
202
                }
        });
    }

    private listTrialJobs(router: Router): void {
        router.get('/trial-jobs', (req: Request, res: Response) => {
            this.nniManager.listTrialJobs(req.query.status).then((jobInfos: TrialJobInfo[]) => {
                jobInfos.forEach((trialJob: TrialJobInfo) => {
                    this.setErrorPathForFailedJob(trialJob);
                });
                res.send(jobInfos);
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
203
                this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
204
205
206
207
208
209
210
211
212
213
            });
        });
    }

    private getTrialJob(router: Router): void {
        router.get('/trial-jobs/:id', (req: Request, res: Response) => {
            this.nniManager.getTrialJob(req.params.id).then((jobDetail: TrialJobInfo) => {
                const jobInfo: TrialJobInfo = this.setErrorPathForFailedJob(jobDetail);
                res.send(jobInfo);
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
214
                this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
215
216
217
218
219
220
            });
        });
    }

    private addTrialJob(router: Router): void {
        router.post('/trial-jobs', async (req: Request, res: Response) => {
221
222
            this.nniManager.addCustomizedTrialJob(JSON.stringify(req.body)).then((sequenceId: number) => {
                res.send({sequenceId});
Deshui Yu's avatar
Deshui Yu committed
223
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
224
                this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
225
226
227
228
229
230
231
232
233
            });
        });
    }

    private cancelTrialJob(router: Router): void {
        router.delete('/trial-jobs/:id', async (req: Request, res: Response) => {
            this.nniManager.cancelTrialJobByUser(req.params.id).then(() => {
                res.send();
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
234
                this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
235
236
237
238
239
            });
        });
    }

    private getMetricData(router: Router): void {
240
        router.get('/metric-data/:job_id*?', async (req: Request, res: Response) => {
Deshui Yu's avatar
Deshui Yu committed
241
            this.nniManager.getMetricData(req.params.job_id, req.query.type).then((metricsData: MetricDataRecord[]) => {
242
243
                res.send(metricsData);
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
244
                this.handleError(err, res);
245
246
247
248
249
250
251
252
253
254
255
            });
        });
    }

    private getMetricDataByRange(router: Router): void {
        router.get('/metric-data-range/:min_seq_id/:max_seq_id', async (req: Request, res: Response) => {
            const minSeqId = Number(req.params.min_seq_id);
            const maxSeqId = Number(req.params.max_seq_id);
            this.nniManager.getMetricDataByRange(minSeqId, maxSeqId).then((metricsData: MetricDataRecord[]) => {
                res.send(metricsData);
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
256
                this.handleError(err, res);
257
258
259
260
261
262
263
            });
        });
    }

    private getLatestMetricData(router: Router): void {
        router.get('/metric-data-latest/', async (req: Request, res: Response) => {
            this.nniManager.getLatestMetricData().then((metricsData: MetricDataRecord[]) => {
Deshui Yu's avatar
Deshui Yu committed
264
265
                res.send(metricsData);
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
266
                this.handleError(err, res);
Deshui Yu's avatar
Deshui Yu committed
267
268
269
270
            });
        });
    }

271
272
273
274
275
    private exportData(router: Router): void {
        router.get('/export-data', (req: Request, res: Response) => {
            this.nniManager.exportData().then((exportedData: string) => {
                res.send(exportedData);
            }).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
276
                this.handleError(err, res);
277
278
279
280
            });
        });
    }

Deshui Yu's avatar
Deshui Yu committed
281
282
283
284
    private setErrorPathForFailedJob(jobInfo: TrialJobInfo): TrialJobInfo {
        if (jobInfo === undefined || jobInfo.status !== 'FAILED' || jobInfo.logPath === undefined) {
            return jobInfo;
        }
chicm-ms's avatar
chicm-ms committed
285
        jobInfo.stderrPath = path.join(jobInfo.logPath, 'stderr');
Deshui Yu's avatar
Deshui Yu committed
286
287
288
289
290

        return jobInfo;
    }
}

291
export function createRestHandler(rs: NNIRestServer): Router {
Deshui Yu's avatar
Deshui Yu committed
292
293
294
295
    const handler: NNIRestHandler = new NNIRestHandler(rs);

    return handler.createRestHandler();
}