restHandler.ts 11.9 KB
Newer Older
Deshui Yu's avatar
Deshui Yu committed
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
29
30
/**
 * 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 { 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';
import { isNewExperiment } from '../common/experimentStartupInfo';
import { getLogger, Logger } from '../common/log';
import { ExperimentProfile, Manager, TrialJobStatistics} from '../common/manager';
31
32
import { ValidationSchemas } from './restValidationSchemas';
import { NNIRestServer } from './nniRestServer';
Deshui Yu's avatar
Deshui Yu committed
33
34
import { TensorBoard } from './tensorboard';

35
36
const expressJoi = require('express-joi-validator');

Deshui Yu's avatar
Deshui Yu committed
37
class NNIRestHandler {
38
    private restServer: NNIRestServer;
Deshui Yu's avatar
Deshui Yu committed
39
40
41
42
    private nniManager: Manager;
    private tb: TensorBoard;
    private log: Logger;

43
    constructor(rs: NNIRestServer) {
Deshui Yu's avatar
Deshui Yu committed
44
45
46
47
48
49
50
51
52
53
54
        this.nniManager = component.get(Manager);
        this.restServer = rs;
        this.tb = new TensorBoard();
        this.log = getLogger();
    }

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

        // tslint:disable-next-line:typedef
        router.use((req: Request, res: Response, next) => {
55
56
57
58
            // Don't log useless empty body content
            if(req.body &&  Object.keys(req.body).length > 0) {
                this.log.info(`${req.method}: ${req.url}: body:\n${JSON.stringify(req.body, undefined, 4)}`);
            }
Deshui Yu's avatar
Deshui Yu committed
59
60
61
62
63
64
65
66
            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
67
        this.version(router);
Deshui Yu's avatar
Deshui Yu committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
        this.checkStatus(router);
        this.getExperimentProfile(router);
        this.updateExperimentProfile(router);
        this.startExperiment(router);
        this.getTrialJobStatistics(router);
        this.setClusterMetaData(router);
        this.listTrialJobs(router);
        this.getTrialJob(router);
        this.addTrialJob(router);
        this.cancelTrialJob(router);
        this.getMetricData(router);
        this.getExample(router);
        this.getTriedParameters(router);
        this.startTensorBoard(router);
        this.stopTensorBoard(router);

84
85
86
87
88
89
90
91
92
        // 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
93
94
95
        return router;
    }

96
    private handle_error(err: Error, res: Response, isFatal: boolean = false): void {
Deshui Yu's avatar
Deshui Yu committed
97
98
99
100
101
102
103
104
        if (err instanceof NNIError && err.name === NNIErrorNames.NOT_FOUND) {
            res.status(404);
        } else {
            res.status(500);
        }
        res.send({
            error: err.message
        });
105
106
107
108
109
110
111
112

        // If it's a fatal error, exit process
        if(isFatal) {
            this.log.critical(err);
            process.exit(1);
        }

        this.log.error(err);
Deshui Yu's avatar
Deshui Yu committed
113
114
    }

Gems Guo's avatar
Gems Guo committed
115
116
117
118
119
120
121
    private version(router: Router): void {
        router.get('/version', async (req: Request, res: Response) => {
            const pkg = await import(path.join(__dirname, '..', 'package.json'));
            res.send(pkg.version);
        });
    }

Deshui Yu's avatar
Deshui Yu committed
122
123
124
125
126
    // 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(() => {
127
                res.send(this.nniManager.getStatus());
Deshui Yu's avatar
Deshui Yu committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
            }).catch(async (err: Error) => {
                this.handle_error(err, res);
                this.log.error(err.message);
                this.log.error(`Database initialize failed, stopping rest server...`);
                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) => {
                this.handle_error(err, res);
            });
        });
    }

    private updateExperimentProfile(router: Router): void {
148
        router.put('/experiment', expressJoi(ValidationSchemas.UPDATEEXPERIMENT), (req: Request, res: Response) => {
Deshui Yu's avatar
Deshui Yu committed
149
150
151
152
153
154
155
156
157
            this.nniManager.updateExperimentProfile(req.body, req.query.update_type).then(() => {
                res.send();
            }).catch((err: Error) => {
                this.handle_error(err, res);
            });
        });
    }

    private startExperiment(router: Router): void {
158
        router.post('/experiment', expressJoi(ValidationSchemas.STARTEXPERIMENT), (req: Request, res: Response) => {
Deshui Yu's avatar
Deshui Yu committed
159
160
161
162
163
164
            if (isNewExperiment()) {
                this.nniManager.startExperiment(req.body).then((eid: string) => {
                    res.send({
                        experiment_id: eid
                    });
                }).catch((err: Error) => {
165
                    // Start experiment is a step of initialization, so any exception thrown is a fatal
Deshui Yu's avatar
Deshui Yu committed
166
167
168
169
170
171
                    this.handle_error(err, res);
                });
            } else {
                this.nniManager.resumeExperiment().then(() => {
                    res.send();
                }).catch((err: Error) => {
172
                    // Resume experiment is a step of initialization, so any exception thrown is a fatal
Deshui Yu's avatar
Deshui Yu committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
                    this.handle_error(err, res);
                });
            }
        });
    }

    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) => {
                this.handle_error(err, res);
            });
        });
    }

    private setClusterMetaData(router: Router): void {
190
191
192
        router.put(
            '/experiment/cluster-metadata', expressJoi(ValidationSchemas.SETCLUSTERMETADATA),
            async (req: Request, res: Response) => {
Deshui Yu's avatar
Deshui Yu committed
193
194
195
196
197
198
199
200
201
            // tslint:disable-next-line:no-any
            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) {
202
203
                // setClusterMetata is a step of initialization, so any exception thrown is a fatal
                this.handle_error(err, res, true);
Deshui Yu's avatar
Deshui Yu committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
            }
        });
    }

    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) => {
                this.handle_error(err, res);
            });
        });
    }

    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) => {
                this.handle_error(err, res);
            });
        });
    }

    private addTrialJob(router: Router): void {
        router.post('/trial-jobs', async (req: Request, res: Response) => {
            this.nniManager.addCustomizedTrialJob(JSON.stringify(req.body)).then(() => {
                res.send();
            }).catch((err: Error) => {
                this.handle_error(err, res);
            });
        });
    }

    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) => {
                this.handle_error(err, res);
            });
        });
    }

    private getMetricData(router: Router): void {
253
        router.get('/metric-data/:job_id*?', async (req: Request, res: Response) => {
Deshui Yu's avatar
Deshui Yu committed
254
255
256
257
258
259
260
261
262
            this.nniManager.getMetricData(req.params.job_id, req.query.type).then((metricsData: MetricDataRecord[]) => {
                res.send(metricsData);
            }).catch((err: Error) => {
                this.handle_error(err, res);
            });
        });
    }

    private startTensorBoard(router: Router): void {
263
        router.post('/tensorboard', expressJoi(ValidationSchemas.STARTTENSORBOARD), async (req: Request, res: Response) => {
Deshui Yu's avatar
Deshui Yu committed
264
265
266
267
268
269
270
271
272
273
274
            const jobIds: string[] = req.query.job_ids.split(',');
            const tensorboardCmd: string | undefined = req.query.tensorboard_cmd;
            this.tb.startTensorBoard(jobIds, tensorboardCmd).then((endPoint: string) => {
                res.send({endPoint: endPoint});
            }).catch((err: Error) => {
                this.handle_error(err, res);
            });
        });
    }

    private stopTensorBoard(router: Router): void {
275
        router.delete('/tensorboard', expressJoi(ValidationSchemas.STOPTENSORBOARD), async (req: Request, res: Response) => {
Deshui Yu's avatar
Deshui Yu committed
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
            const endPoint: string = req.query.endpoint;
            this.tb.stopTensorBoard(endPoint).then(() => {
                res.send();
            }).catch((err: Error) => {
                this.handle_error(err, res);
            });
        });
    }

    private getExample(router: Router): void {
        // tslint:disable-next-line:no-empty
        router.get('/example', async (req: Request, res: Response) => {
        });
    }

    private getTriedParameters(router: Router): void {
        // tslint:disable-next-line:no-empty
        router.get('/tried-parameters', async (req: Request, res: Response) => {
        });
    }

    private setErrorPathForFailedJob(jobInfo: TrialJobInfo): TrialJobInfo {
        if (jobInfo === undefined || jobInfo.status !== 'FAILED' || jobInfo.logPath === undefined) {
            return jobInfo;
        }
chicm-ms's avatar
chicm-ms committed
301
        jobInfo.stderrPath = path.join(jobInfo.logPath, 'stderr');
Deshui Yu's avatar
Deshui Yu committed
302
303
304
305
306

        return jobInfo;
    }
}

307
export function createRestHandler(rs: NNIRestServer): Router {
Deshui Yu's avatar
Deshui Yu committed
308
309
310
311
    const handler: NNIRestHandler = new NNIRestHandler(rs);

    return handler.createRestHandler();
}