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

4
5
6
7
import bodyParser from 'body-parser';
import express from 'express';
import httpProxy from 'http-proxy';
import path from 'path';
8
9
import * as component from '../common/component';
import { RestServer } from '../common/restServer'
chicm-ms's avatar
chicm-ms committed
10
import { getLogDir } from '../common/utils';
11
import { createRestHandler } from './restHandler';
12
import { getAPIRootUrl, getPrefixUrl } from '../common/experimentStartupInfo';
13
14
15
16

/**
 * NNI Main rest server, provides rest API to support
 * # nnictl CLI tool
goooxu's avatar
goooxu committed
17
 * # NNI WebUI
18
 *
19
20
 */
@component.Singleton
goooxu's avatar
goooxu committed
21
export class NNIRestServer extends RestServer {
chicm-ms's avatar
chicm-ms committed
22
    private readonly LOGS_ROOT_URL: string = '/logs';
Yuge Zhang's avatar
Yuge Zhang committed
23
    protected netronProxy: any = null;
24
    protected API_ROOT_URL: string = '/api/v1/nni';
25
26
27
28
29
30

    /**
     * constructor to provide NNIRestServer's own rest property, e.g. port
     */
    constructor() {
        super();
31
        this.API_ROOT_URL = getAPIRootUrl();
Yuge Zhang's avatar
Yuge Zhang committed
32
        this.netronProxy = httpProxy.createProxyServer();
33
34
35
36
37
38
    }

    /**
     * NNIRestServer's own router registration
     */
    protected registerRestHandler(): void {
39
        this.app.use(getPrefixUrl(), express.static('static'));
40
        this.app.use(bodyParser.json({limit: '50mb'}));
41
        this.app.use(this.API_ROOT_URL, createRestHandler(this));
chicm-ms's avatar
chicm-ms committed
42
        this.app.use(this.LOGS_ROOT_URL, express.static(getLogDir()));
Yuge Zhang's avatar
Yuge Zhang committed
43
44
45
46
47
48
49
50
        this.app.all('/netron/*', (req: express.Request, res: express.Response) => {
            delete req.headers.host;
            req.url = req.url.replace('/netron', '/');
            this.netronProxy.web(req, res, {
                changeOrigin: true,
                target: 'https://netron.app'
            });
        });
51
        this.app.get(`${getPrefixUrl()}/*`, (_req: express.Request, res: express.Response) => {
goooxu's avatar
goooxu committed
52
53
            res.sendFile(path.resolve('static/index.html'));
        });
54
55
    }
}