main.ts 7.28 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

'use strict';

import { Container, Scope } from 'typescript-ioc';

8
import * as fs from 'fs';
9
import * as path from 'path';
10
import * as component from './common/component';
Deshui Yu's avatar
Deshui Yu committed
11
12
import { Database, DataStore } from './common/datastore';
import { setExperimentStartupInfo } from './common/experimentStartupInfo';
chicm-ms's avatar
chicm-ms committed
13
import { getLogger, Logger, logLevelNameMap } from './common/log';
SparkSnail's avatar
SparkSnail committed
14
import { Manager, ExperimentStartUpMode } from './common/manager';
Deshui Yu's avatar
Deshui Yu committed
15
import { TrainingService } from './common/trainingService';
16
import { getLogDir, mkDirP, parseArg, uniqueString } from './common/utils';
Deshui Yu's avatar
Deshui Yu committed
17
18
19
import { NNIDataStore } from './core/nniDataStore';
import { NNIManager } from './core/nnimanager';
import { SqlDB } from './core/sqlDatabase';
20
import { NNIRestServer } from './rest_server/nniRestServer';
21
22
23
import { FrameworkControllerTrainingService } from './training_service/kubernetes/frameworkcontroller/frameworkcontrollerTrainingService';
import { KubeflowTrainingService } from './training_service/kubernetes/kubeflow/kubeflowTrainingService';
import { LocalTrainingService } from './training_service/local/localTrainingService';
24
25
import { PAIK8STrainingService } from './training_service/pai/paiK8S/paiK8STrainingService';
import { PAIYarnTrainingService } from './training_service/pai/paiYarn/paiYarnTrainingService';
Deshui Yu's avatar
Deshui Yu committed
26
27
28
29
import {
    RemoteMachineTrainingService
} from './training_service/remote_machine/remoteMachineTrainingService';

30
31
function initStartupInfo(
    startExpMode: string, resumeExperimentId: string, basePort: number,
SparkSnail's avatar
SparkSnail committed
32
33
    logDirectory: string, experimentLogLevel: string, readonly: boolean): void {
    const createNew: boolean = (startExpMode === ExperimentStartUpMode.NEW);
Deshui Yu's avatar
Deshui Yu committed
34
    const expId: string = createNew ? uniqueString(8) : resumeExperimentId;
SparkSnail's avatar
SparkSnail committed
35
    setExperimentStartupInfo(createNew, expId, basePort, logDirectory, experimentLogLevel, readonly);
Deshui Yu's avatar
Deshui Yu committed
36
37
}

38
async function initContainer(foreground: boolean, platformMode: string, logFileName?: string): Promise<void> {
Deshui Yu's avatar
Deshui Yu committed
39
    if (platformMode === 'local') {
40
41
42
        Container.bind(TrainingService)
            .to(LocalTrainingService)
            .scope(Scope.Singleton);
Deshui Yu's avatar
Deshui Yu committed
43
    } else if (platformMode === 'remote') {
44
45
46
        Container.bind(TrainingService)
            .to(RemoteMachineTrainingService)
            .scope(Scope.Singleton);
47
    } else if (platformMode === 'pai') {
48
        Container.bind(TrainingService)
49
50
51
52
53
            .to(PAIK8STrainingService)
            .scope(Scope.Singleton);
    } else if (platformMode === 'paiYarn') {
            Container.bind(TrainingService)
            .to(PAIYarnTrainingService)
54
            .scope(Scope.Singleton);
55
    } else if (platformMode === 'kubeflow') {
56
57
58
        Container.bind(TrainingService)
            .to(KubeflowTrainingService)
            .scope(Scope.Singleton);
59
    } else if (platformMode === 'frameworkcontroller') {
60
61
62
63
        Container.bind(TrainingService)
            .to(FrameworkControllerTrainingService)
            .scope(Scope.Singleton);
    } else {
chicm-ms's avatar
chicm-ms committed
64
        throw new Error(`Error: unsupported mode: ${platformMode}`);
Deshui Yu's avatar
Deshui Yu committed
65
    }
66
67
68
69
70
71
72
73
74
    Container.bind(Manager)
        .to(NNIManager)
        .scope(Scope.Singleton);
    Container.bind(Database)
        .to(SqlDB)
        .scope(Scope.Singleton);
    Container.bind(DataStore)
        .to(NNIDataStore)
        .scope(Scope.Singleton);
75
76
77
78
79
80
    const DEFAULT_LOGFILE: string = path.join(getLogDir(), 'nnimanager.log');
    if (foreground) {
        logFileName = undefined;
    } else if (logFileName === undefined) {
        logFileName = DEFAULT_LOGFILE;
    }
SparkSnail's avatar
SparkSnail committed
81
82
83
    Container.bind(Logger).provider({
        get: (): Logger => new Logger(logFileName)
    });
Deshui Yu's avatar
Deshui Yu committed
84
85
86
87
88
89
    const ds: DataStore = component.get(DataStore);

    await ds.init();
}

function usage(): void {
90
    console.info('usage: node main.js --port <port> --mode \
91
    <local/remote/pai/kubeflow/frameworkcontroller/paiYarn> --start_mode <new/resume> --experiment_id <id> --foreground <true/false>');
Deshui Yu's avatar
Deshui Yu committed
92
93
94
}

const strPort: string = parseArg(['--port', '-p']);
goooxu's avatar
goooxu committed
95
96
97
if (!strPort || strPort.length === 0) {
    usage();
    process.exit(1);
Deshui Yu's avatar
Deshui Yu committed
98
99
}

100
101
102
103
104
105
106
107
const foregroundArg: string = parseArg(['--foreground', '-f']);
if (!('true' || 'false').includes(foregroundArg.toLowerCase())) {
    console.log(`FATAL: foreground property should only be true or false`);
    usage();
    process.exit(1);
}
const foreground: boolean = foregroundArg.toLowerCase() === 'true' ? true : false;

goooxu's avatar
goooxu committed
108
109
const port: number = parseInt(strPort, 10);

Deshui Yu's avatar
Deshui Yu committed
110
const mode: string = parseArg(['--mode', '-m']);
111
if (!['local', 'remote', 'pai', 'kubeflow', 'frameworkcontroller', 'paiYarn'].includes(mode)) {
112
    console.log(`FATAL: unknown mode: ${mode}`);
Deshui Yu's avatar
Deshui Yu committed
113
114
115
116
117
    usage();
    process.exit(1);
}

const startMode: string = parseArg(['--start_mode', '-s']);
SparkSnail's avatar
SparkSnail committed
118
if (![ExperimentStartUpMode.NEW, ExperimentStartUpMode.RESUME].includes(startMode)) {
119
    console.log(`FATAL: unknown start_mode: ${startMode}`);
Deshui Yu's avatar
Deshui Yu committed
120
121
122
123
124
    usage();
    process.exit(1);
}

const experimentId: string = parseArg(['--experiment_id', '-id']);
SparkSnail's avatar
SparkSnail committed
125
126
if ((startMode === ExperimentStartUpMode.RESUME) && experimentId.trim().length < 1) {
    console.log(`FATAL: cannot resume the experiment, invalid experiment_id: ${experimentId}`);
Deshui Yu's avatar
Deshui Yu committed
127
128
129
130
    usage();
    process.exit(1);
}

131
132
133
134
135
136
137
138
const logDir: string = parseArg(['--log_dir', '-ld']);
if (logDir.length > 0) {
    if (!fs.existsSync(logDir)) {
        console.log(`FATAL: log_dir ${logDir} does not exist`);
    }
}

const logLevel: string = parseArg(['--log_level', '-ll']);
chicm-ms's avatar
chicm-ms committed
139
if (logLevel.length > 0 && !logLevelNameMap.has(logLevel)) {
140
141
142
    console.log(`FATAL: invalid log_level: ${logLevel}`);
}

SparkSnail's avatar
SparkSnail committed
143
144
145
146
147
148
149
150
151
const readonlyArg: string = parseArg(['--readonly', '-r']);
if (!('true' || 'false').includes(readonlyArg.toLowerCase())) {
    console.log(`FATAL: readonly property should only be true or false`);
    usage();
    process.exit(1);
}
const readonly = readonlyArg.toLowerCase() == 'true' ? true : false;

initStartupInfo(startMode, experimentId, port, logDir, logLevel, readonly);
Deshui Yu's avatar
Deshui Yu committed
152

153
154
mkDirP(getLogDir())
    .then(async () => {
Deshui Yu's avatar
Deshui Yu committed
155
    try {
156
        await initContainer(foreground, mode);
157
        const restServer: NNIRestServer = component.get(NNIRestServer);
158
        await restServer.start();
SparkSnail's avatar
SparkSnail committed
159
        const log: Logger = getLogger();
Deshui Yu's avatar
Deshui Yu committed
160
161
        log.info(`Rest server listening on: ${restServer.endPoint}`);
    } catch (err) {
SparkSnail's avatar
SparkSnail committed
162
        const log: Logger = getLogger();
Deshui Yu's avatar
Deshui Yu committed
163
        log.error(`${err.stack}`);
164
        throw err;
Deshui Yu's avatar
Deshui Yu committed
165
    }
166
167
})
.catch((err: Error) => {
Deshui Yu's avatar
Deshui Yu committed
168
169
    console.error(`Failed to create log dir: ${err.stack}`);
});
170

171
172
173
174
175
176
177
178
179
function getStopSignal(): any {
    if (process.platform === "win32") {
        return 'SIGBREAK';
    }
    else{
        return 'SIGTERM';
    }
}

180
181
182
183
184
185
186
187
188
function getCtrlCSignal(): any {
    return 'SIGINT';
}

process.on(getCtrlCSignal(), async () => {
    const log: Logger = getLogger();
    log.info(`Get SIGINT signal!`);
});

189
process.on(getStopSignal(), async () => {
190
    const log: Logger = getLogger();
SparkSnail's avatar
SparkSnail committed
191
    let hasError: boolean = false;
192
    try {
SparkSnail's avatar
SparkSnail committed
193
194
195
196
197
198
        const nniManager: Manager = component.get(Manager);
        await nniManager.stopExperiment();
        const ds: DataStore = component.get(DataStore);
        await ds.close();
        const restServer: NNIRestServer = component.get(NNIRestServer);
        await restServer.stop();
199
    } catch (err) {
SparkSnail's avatar
SparkSnail committed
200
201
        hasError = true;
        log.error(`${err.stack}`);
202
    } finally {
SparkSnail's avatar
SparkSnail committed
203
        await log.close();
204
        process.exit(hasError ? 1 : 0);
SparkSnail's avatar
SparkSnail committed
205
    }
206
});