nniRestServer.ts 1.85 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

'use strict';

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

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

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

    /**
     * NNIRestServer's own router registration
     */
    protected registerRestHandler(): void {
goooxu's avatar
goooxu committed
41
        this.app.use(express.static('static'));
42
        this.app.use(bodyParser.json({limit: '50mb'}));
43
        this.app.use(this.API_ROOT_URL, createRestHandler(this));
chicm-ms's avatar
chicm-ms committed
44
        this.app.use(this.LOGS_ROOT_URL, express.static(getLogDir()));
Yuge Zhang's avatar
Yuge Zhang committed
45
46
47
48
49
50
51
52
        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'
            });
        });
goooxu's avatar
goooxu committed
53
54
55
        this.app.get('*', (req: express.Request, res: express.Response) => {
            res.sendFile(path.resolve('static/index.html'));
        });
56
57
    }
}