remoteMachineTrainingService.ts 30.7 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

'use strict';

6
import * as assert from 'assert';
Deshui Yu's avatar
Deshui Yu committed
7
8
9
import { EventEmitter } from 'events';
import * as fs from 'fs';
import * as path from 'path';
chicm-ms's avatar
chicm-ms committed
10
import { Client } from 'ssh2';
Deshui Yu's avatar
Deshui Yu committed
11
12
13
import { Deferred } from 'ts-deferred';
import { String } from 'typescript-string-operations';
import * as component from '../../common/component';
SparkSnail's avatar
SparkSnail committed
14
import { NNIError, NNIErrorNames } from '../../common/errors';
15
import { getExperimentId } from '../../common/experimentStartupInfo';
Deshui Yu's avatar
Deshui Yu committed
16
17
18
import { getLogger, Logger } from '../../common/log';
import { ObservableTimer } from '../../common/observableTimer';
import {
19
    HyperParameters, NNIManagerIpConfig, TrainingService, TrialJobApplicationForm,
20
    TrialJobDetail, TrialJobMetric
Deshui Yu's avatar
Deshui Yu committed
21
} from '../../common/trainingService';
22
23
24
25
26
import {
    delay, generateParamFileName, getExperimentRootDir, getIPV4Address, getJobCancelStatus, getRemoteTmpDir,
    getVersion, uniqueString, unixPathJoin
} from '../../common/utils';
import { CONTAINER_INSTALL_NNI_SHELL_FORMAT } from '../common/containerJobData';
27
import { GPUSummary } from '../common/gpuData';
28
29
import { TrialConfig } from '../common/trialConfig';
import { TrialConfigMetadataKey } from '../common/trialConfigMetadataKey';
chicm-ms's avatar
chicm-ms committed
30
import { execCopydir, execMkdir, validateCodeDir, getGpuMetricsCollectorBashScriptContent } from '../common/util';
Deshui Yu's avatar
Deshui Yu committed
31
32
import { GPUScheduler } from './gpuScheduler';
import {
chicm-ms's avatar
chicm-ms committed
33
    RemoteCommandResult, REMOTEMACHINE_TRIAL_COMMAND_FORMAT, RemoteMachineMeta,
34
    RemoteMachineScheduleInfo, RemoteMachineScheduleResult, RemoteMachineTrialJobDetail,
chicm-ms's avatar
chicm-ms committed
35
    ScheduleResultType, SSHClientManager
Deshui Yu's avatar
Deshui Yu committed
36
} from './remoteMachineData';
SparkSnail's avatar
SparkSnail committed
37
import { RemoteMachineJobRestServer } from './remoteMachineJobRestServer';
38
import { SSHClientUtility } from './sshClientUtility';
Deshui Yu's avatar
Deshui Yu committed
39
40
41
42

/**
 * Training Service implementation for Remote Machine (Linux)
 */
SparkSnail's avatar
SparkSnail committed
43
@component.Singleton
Deshui Yu's avatar
Deshui Yu committed
44
class RemoteMachineTrainingService implements TrainingService {
45
46
47
48
49
50
    private readonly machineSSHClientMap: Map<RemoteMachineMeta, SSHClientManager>; //machine ssh client map
    private readonly trialSSHClientMap: Map<string, Client>; //trial ssh client map
    private readonly trialJobsMap: Map<string, RemoteMachineTrialJobDetail>;
    private readonly MAX_TRIAL_NUMBER_PER_SSHCONNECTION: number = 5; // every ssh client has a max trial concurrency number
    private readonly expRootDir: string;
    private readonly remoteExpRootDir: string;
51
    private trialConfig: TrialConfig | undefined;
52
    private gpuScheduler?: GPUScheduler;
53
54
    private readonly jobQueue: string[];
    private readonly timer: ObservableTimer;
Deshui Yu's avatar
Deshui Yu committed
55
    private stopping: boolean = false;
56
57
    private readonly metricsEmitter: EventEmitter;
    private readonly log: Logger;
58
    private isMultiPhase: boolean = false;
59
    private trialSequenceId: number;
SparkSnail's avatar
SparkSnail committed
60
    private remoteRestServerPort?: number;
61
    private readonly remoteOS: string;
SparkSnail's avatar
SparkSnail committed
62
    private nniManagerIpConfig?: NNIManagerIpConfig;
63
    private versionCheck: boolean = true;
SparkSnail's avatar
SparkSnail committed
64
    private logCollection: string;
Deshui Yu's avatar
Deshui Yu committed
65
66

    constructor(@component.Inject timer: ObservableTimer) {
67
        this.remoteOS = 'linux';
Deshui Yu's avatar
Deshui Yu committed
68
69
        this.metricsEmitter = new EventEmitter();
        this.trialJobsMap = new Map<string, RemoteMachineTrialJobDetail>();
SparkSnail's avatar
SparkSnail committed
70
71
        this.trialSSHClientMap = new Map<string, Client>();
        this.machineSSHClientMap = new Map<RemoteMachineMeta, SSHClientManager>();
Deshui Yu's avatar
Deshui Yu committed
72
73
        this.jobQueue = [];
        this.expRootDir = getExperimentRootDir();
74
        this.remoteExpRootDir = this.getRemoteExperimentRootDir();
Deshui Yu's avatar
Deshui Yu committed
75
76
        this.timer = timer;
        this.log = getLogger();
77
        this.trialSequenceId = -1;
SparkSnail's avatar
SparkSnail committed
78
        this.logCollection = 'none';
chicm-ms's avatar
chicm-ms committed
79
        this.log.info('Construct remote machine training service.');
Deshui Yu's avatar
Deshui Yu committed
80
81
82
83
84
85
    }

    /**
     * Loop to launch trial jobs and collect trial metrics
     */
    public async run(): Promise<void> {
SparkSnail's avatar
SparkSnail committed
86
87
        const restServer: RemoteMachineJobRestServer = component.get(RemoteMachineJobRestServer);
        await restServer.start();
88
        restServer.setEnableVersionCheck = this.versionCheck;
chicm-ms's avatar
chicm-ms committed
89
        this.log.info('Run remote machine training service.');
Deshui Yu's avatar
Deshui Yu committed
90
91
        while (!this.stopping) {
            while (this.jobQueue.length > 0) {
SparkSnail's avatar
SparkSnail committed
92
                this.updateGpuReservation();
Deshui Yu's avatar
Deshui Yu committed
93
                const trialJobId: string = this.jobQueue[0];
chicm-ms's avatar
chicm-ms committed
94
                const prepareResult: boolean = await this.prepareTrialJob(trialJobId);
Deshui Yu's avatar
Deshui Yu committed
95
96
97
98
                if (prepareResult) {
                    // Remove trial job with trialJobId from job queue
                    this.jobQueue.shift();
                } else {
99
                    // Break the while loop since no GPU resource is available right now,
Deshui Yu's avatar
Deshui Yu committed
100
101
102
                    // Wait to schedule job in next time iteration
                    break;
                }
103
            }
104
            if (restServer.getErrorMessage !== undefined) {
105
106
107
                throw new Error(restServer.getErrorMessage);
                this.stopping = true;
            }
Deshui Yu's avatar
Deshui Yu committed
108
109
            await delay(3000);
        }
chicm-ms's avatar
chicm-ms committed
110
        this.log.info('Remote machine training service exit.');
Deshui Yu's avatar
Deshui Yu committed
111
    }
112

SparkSnail's avatar
SparkSnail committed
113
114
    /**
     * give trial a ssh connection
115
     * @param trial remote machine trial job detail
SparkSnail's avatar
SparkSnail committed
116
117
118
     */
    public async allocateSSHClientForTrial(trial: RemoteMachineTrialJobDetail): Promise<void> {
        const deferred: Deferred<void> = new Deferred<void>();
119
        if (trial.rmMeta === undefined) {
SparkSnail's avatar
SparkSnail committed
120
121
            throw new Error(`rmMeta not set in trial ${trial.id}`);
        }
122
123
        const sshClientManager: SSHClientManager | undefined = this.machineSSHClientMap.get(trial.rmMeta);
        if (sshClientManager === undefined) {
SparkSnail's avatar
SparkSnail committed
124
125
            throw new Error(`remoteSSHClient not initialized`);
        }
126
        const sshClient: Client = await sshClientManager.getAvailableSSHClient();
SparkSnail's avatar
SparkSnail committed
127
128
        this.trialSSHClientMap.set(trial.id, sshClient);
        deferred.resolve();
129

SparkSnail's avatar
SparkSnail committed
130
131
        return deferred.promise;
    }
132

SparkSnail's avatar
SparkSnail committed
133
134
    /**
     * If a trial is finished, release the connection resource
135
     * @param trial remote machine trial job detail
SparkSnail's avatar
SparkSnail committed
136
137
     */
    public releaseTrialSSHClient(trial: RemoteMachineTrialJobDetail): void {
138
        if (trial.rmMeta === undefined) {
SparkSnail's avatar
SparkSnail committed
139
140
            throw new Error(`rmMeta not set in trial ${trial.id}`);
        }
141
142
        const sshClientManager: SSHClientManager | undefined = this.machineSSHClientMap.get(trial.rmMeta);
        if (sshClientManager === undefined) {
SparkSnail's avatar
SparkSnail committed
143
144
145
146
            throw new Error(`sshClientManager not initialized`);
        }
        sshClientManager.releaseConnection(this.trialSSHClientMap.get(trial.id));
    }
Deshui Yu's avatar
Deshui Yu committed
147
148
149
150

    /**
     * List submitted trial jobs
     */
151
    public async listTrialJobs(): Promise<TrialJobDetail[]> {
Deshui Yu's avatar
Deshui Yu committed
152
153
154
        const jobs: TrialJobDetail[] = [];
        const deferred: Deferred<TrialJobDetail[]> = new Deferred<TrialJobDetail[]>();

155
        for (const [key, value] of this.trialJobsMap) {
156
            jobs.push(await this.getTrialJob(key));
157
        }
Deshui Yu's avatar
Deshui Yu committed
158
159
160
161
162
163
164
165
166
167
168
        deferred.resolve(jobs);

        return deferred.promise;
    }

    /**
     * Get trial job detail information
     * @param trialJobId ID of trial job
     */
    public async getTrialJob(trialJobId: string): Promise<TrialJobDetail> {
        const trialJob: RemoteMachineTrialJobDetail | undefined = this.trialJobsMap.get(trialJobId);
169
        if (trialJob === undefined) {
Deshui Yu's avatar
Deshui Yu committed
170
171
172
173
174
175
176
177
            throw new NNIError(NNIErrorNames.NOT_FOUND, `trial job id ${trialJobId} not found`);
        }
        //TO DO: add another job status, and design new job status change logic
        if (trialJob.status === 'RUNNING' || trialJob.status === 'UNKNOWN') {
            // Get ssh client where the job is running
            if (trialJob.rmMeta === undefined) {
                throw new Error(`rmMeta not set for submitted job ${trialJobId}`);
            }
SparkSnail's avatar
SparkSnail committed
178
            const sshClient: Client | undefined  = this.trialSSHClientMap.get(trialJob.id);
179
            if (sshClient === undefined) {
Deshui Yu's avatar
Deshui Yu committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
                throw new Error(`Invalid job id: ${trialJobId}, cannot find ssh client`);
            }

            return this.updateTrialJobStatus(trialJob, sshClient);
        } else {
            return trialJob;
        }
    }

    /**
     * Add job metrics listener
     * @param listener callback listener
     */
    public addTrialJobMetricListener(listener: (metric: TrialJobMetric) => void): void {
        this.metricsEmitter.on('metric', listener);
    }

    /**
     * Remove job metrics listener
     * @param listener callback listener
     */
    public removeTrialJobMetricListener(listener: (metric: TrialJobMetric) => void): void {
        this.metricsEmitter.off('metric', listener);
    }

    /**
     * Submit trial job
     * @param form trial job description form
     */
209
    // tslint:disable-next-line:informative-docs
210
    public async submitTrialJob(form: TrialJobApplicationForm): Promise<TrialJobDetail> {
211
        if (this.trialConfig === undefined) {
Deshui Yu's avatar
Deshui Yu committed
212
213
214
            throw new Error('trial config is not initialized');
        }

215
216
217
        // Generate trial job id(random)
        const trialJobId: string = uniqueString(5);
        const trialWorkingFolder: string = unixPathJoin(this.remoteExpRootDir, 'trials', trialJobId);
Deshui Yu's avatar
Deshui Yu committed
218

219
220
221
222
223
224
225
226
227
        const trialJobDetail: RemoteMachineTrialJobDetail = new RemoteMachineTrialJobDetail(
            trialJobId,
            'WAITING',
            Date.now(),
            trialWorkingFolder,
            form
        );
        this.jobQueue.push(trialJobId);
        this.trialJobsMap.set(trialJobId, trialJobDetail);
228

229
        return Promise.resolve(trialJobDetail);
Deshui Yu's avatar
Deshui Yu committed
230
231
    }

232
233
234
235
236
    /**
     * Update trial job for multi-phase
     * @param trialJobId trial job id
     * @param form job application form
     */
237
    public async updateTrialJob(trialJobId: string, form: TrialJobApplicationForm): Promise<TrialJobDetail> {
chicm-ms's avatar
chicm-ms committed
238
239
240
241
        const trialJobDetail: undefined | TrialJobDetail = this.trialJobsMap.get(trialJobId);
        if (trialJobDetail === undefined) {
            throw new Error(`updateTrialJob failed: ${trialJobId} not found`);
        }
chicm-ms's avatar
chicm-ms committed
242
        await this.writeParameterFile(trialJobId, form.hyperParameters);
chicm-ms's avatar
chicm-ms committed
243
244

        return trialJobDetail;
245
    }
246

247
248
249
250
    /**
     * Is multiphase job supported in current training service
     */
    public get isMultiPhaseJobSupported(): boolean {
251
        return true;
252
253
    }

Deshui Yu's avatar
Deshui Yu committed
254
255
256
257
    /**
     * Cancel trial job
     * @param trialJobId ID of trial job
     */
258
    // tslint:disable:informative-docs no-unsafe-any
QuanluZhang's avatar
QuanluZhang committed
259
    public async cancelTrialJob(trialJobId: string, isEarlyStopped: boolean = false): Promise<void> {
Deshui Yu's avatar
Deshui Yu committed
260
261
        const deferred: Deferred<void> = new Deferred<void>();
        const trialJob: RemoteMachineTrialJobDetail | undefined = this.trialJobsMap.get(trialJobId);
262
        if (trialJob === undefined) {
Deshui Yu's avatar
Deshui Yu committed
263
264
265
266
267
            deferred.reject();
            throw new Error(`trial job id ${trialJobId} not found`);
        }

        // Remove the job with trialJobId from job queue
chicm-ms's avatar
chicm-ms committed
268
        const index: number = this.jobQueue.indexOf(trialJobId);
269
        if (index >= 0) {
Deshui Yu's avatar
Deshui Yu committed
270
271
272
273
274
275
            this.jobQueue.splice(index, 1);
        }

        // Get ssh client where the job is running
        if (trialJob.rmMeta !== undefined) {
            // If the trial job is already scheduled, check its status and kill the trial process in remote machine
SparkSnail's avatar
SparkSnail committed
276
            const sshClient: Client | undefined = this.trialSSHClientMap.get(trialJob.id);
277
            if (sshClient === undefined) {
Deshui Yu's avatar
Deshui Yu committed
278
279
280
281
282
283
                deferred.reject();
                throw new Error(`Invalid job id ${trialJobId}, cannot find ssh client`);
            }

            const jobpidPath: string = this.getJobPidPath(trialJob.id);
            try {
284
285
                // Mark the toEarlyStop tag here
                trialJob.isEarlyStopped = isEarlyStopped;
Deshui Yu's avatar
Deshui Yu committed
286
                await SSHClientUtility.remoteExeCommand(`pkill -P \`cat ${jobpidPath}\``, sshClient);
SparkSnail's avatar
SparkSnail committed
287
                this.releaseTrialSSHClient(trialJob);
Deshui Yu's avatar
Deshui Yu committed
288
289
290
291
292
293
            } catch (error) {
                // Not handle the error since pkill failed will not impact trial job's current status
                this.log.error(`remoteTrainingService.cancelTrialJob: ${error.message}`);
            }
        } else {
            // Job is not scheduled yet, set status to 'USER_CANCELLED' directly
QuanluZhang's avatar
QuanluZhang committed
294
295
            assert(isEarlyStopped === false, 'isEarlyStopped is not supposed to be true here.');
            trialJob.status = getJobCancelStatus(isEarlyStopped);
Deshui Yu's avatar
Deshui Yu committed
296
297
298
299
300
301
302
303
304
305
306
307
        }
    }

    /**
     * Set culster metadata
     * @param key metadata key
     * //1. MACHINE_LIST -- create ssh client connect of machine list
     * //2. TRIAL_CONFIG -- trial configuration
     * @param value metadata value
     */
    public async setClusterMetadata(key: string, value: string): Promise<void> {
        switch (key) {
SparkSnail's avatar
SparkSnail committed
308
309
310
            case TrialConfigMetadataKey.NNI_MANAGER_IP:
                this.nniManagerIpConfig = <NNIManagerIpConfig>JSON.parse(value);
                break;
311
            case TrialConfigMetadataKey.MACHINE_LIST:
Deshui Yu's avatar
Deshui Yu committed
312
                await this.setupConnections(value);
313
                this.gpuScheduler = new GPUScheduler(this.machineSSHClientMap);
Deshui Yu's avatar
Deshui Yu committed
314
                break;
chicm-ms's avatar
chicm-ms committed
315
            case TrialConfigMetadataKey.TRIAL_CONFIG: {
316
                const remoteMachineTrailConfig: TrialConfig = <TrialConfig>JSON.parse(value);
Deshui Yu's avatar
Deshui Yu committed
317
                // Parse trial config failed, throw Error
318
                if (remoteMachineTrailConfig === undefined) {
Deshui Yu's avatar
Deshui Yu committed
319
320
321
                    throw new Error('trial config parsed failed');
                }
                // codeDir is not a valid directory, throw Error
322
323
324
                // tslint:disable-next-line:non-literal-fs-path
                if (!fs.lstatSync(remoteMachineTrailConfig.codeDir)
                  .isDirectory()) {
Deshui Yu's avatar
Deshui Yu committed
325
326
                    throw new Error(`codeDir ${remoteMachineTrailConfig.codeDir} is not a directory`);
                }
327
328
329
330

                // Validate to make sure codeDir doesn't have too many files
                try {
                    await validateCodeDir(remoteMachineTrailConfig.codeDir);
331
                } catch (error) {
332
                    this.log.error(error);
333

334
                    return Promise.reject(new Error(error));
335
336
                }

Deshui Yu's avatar
Deshui Yu committed
337
338
                this.trialConfig = remoteMachineTrailConfig;
                break;
chicm-ms's avatar
chicm-ms committed
339
            }
340
341
342
            case TrialConfigMetadataKey.MULTI_PHASE:
                this.isMultiPhase = (value === 'true' || value === 'True');
                break;
343
344
345
            case TrialConfigMetadataKey.VERSION_CHECK:
                this.versionCheck = (value === 'true' || value === 'True');
                break;
SparkSnail's avatar
SparkSnail committed
346
347
348
            case TrialConfigMetadataKey.LOG_COLLECTION:
                this.logCollection = value;
                break;
Deshui Yu's avatar
Deshui Yu committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
            default:
                //Reject for unknown keys
                throw new Error(`Uknown key: ${key}`);
        }
    }

    /**
     * Get culster metadata
     * @param key metadata key
     */
    public getClusterMetadata(key: string): Promise<string> {
        const deferred: Deferred<string> = new Deferred<string>();

        return deferred.promise;
    }
364

SparkSnail's avatar
SparkSnail committed
365
    /**
366
     * cleanup() has a time out of 10s to clean remote connections
SparkSnail's avatar
SparkSnail committed
367
368
     */
    public async cleanUp(): Promise<void> {
chicm-ms's avatar
chicm-ms committed
369
        this.log.info('Stopping remote machine training service...');
Deshui Yu's avatar
Deshui Yu committed
370
        this.stopping = true;
SparkSnail's avatar
SparkSnail committed
371
372
        await Promise.race([delay(10000), this.cleanupConnections()]);
    }
373

374
375
376
377
    /**
     * remove gpu reversion when job is not running
     */
    private updateGpuReservation(): void {
378
379
380
381
382
        if (this.gpuScheduler) {
            for (const [key, value] of this.trialJobsMap) {
                if (!['WAITING', 'RUNNING'].includes(value.status)) {
                    this.gpuScheduler.removeGpuReservation(key, this.trialJobsMap);
                }
383
384
385
386
            }
        }
    }

SparkSnail's avatar
SparkSnail committed
387
388
389
390
    /**
     * stop gpu_metric_collector process in remote machine and remove unused scripts
     */
    private async cleanupConnections(): Promise<void> {
391
        try {
SparkSnail's avatar
SparkSnail committed
392
            for (const [rmMeta, sshClientManager] of this.machineSSHClientMap.entries()) {
393
394
395
                const jobpidPath: string = unixPathJoin(this.getRemoteScriptsPath(rmMeta.username), 'pid');
                const client: Client | undefined = sshClientManager.getFirstSSHClient();
                if (client !== undefined) {
SparkSnail's avatar
SparkSnail committed
396
397
398
399
                    await SSHClientUtility.remoteExeCommand(`pkill -P \`cat ${jobpidPath}\``, client);
                    await SSHClientUtility.remoteExeCommand(`rm -rf ${this.getRemoteScriptsPath(rmMeta.username)}`, client);
                }
                sshClientManager.closeAllSSHClient();
SparkSnail's avatar
SparkSnail committed
400
            }
401
        } catch (error) {
SparkSnail's avatar
SparkSnail committed
402
403
404
            //ignore error, this function is called to cleanup remote connections when experiment is stopping
            this.log.error(`Cleanup connection exception, error is ${error.message}`);
        }
Deshui Yu's avatar
Deshui Yu committed
405
406

        return Promise.resolve();
407
408
    }

Deshui Yu's avatar
Deshui Yu committed
409
    private async setupConnections(machineList: string): Promise<void> {
chicm-ms's avatar
chicm-ms committed
410
        this.log.debug(`Connecting to remote machines: ${machineList}`);
Deshui Yu's avatar
Deshui Yu committed
411
412
413
414
        const deferred: Deferred<void> = new Deferred<void>();
        //TO DO: verify if value's format is wrong, and json parse failed, how to handle error
        const rmMetaList: RemoteMachineMeta[] = <RemoteMachineMeta[]>JSON.parse(machineList);
        let connectedRMNum: number = 0;
SparkSnail's avatar
SparkSnail committed
415

SparkSnail's avatar
SparkSnail committed
416
        rmMetaList.forEach(async (rmMeta: RemoteMachineMeta) => {
417
            rmMeta.occupiedGpuIndexMap = new Map<number, number>();
418
419
            const sshClientManager: SSHClientManager = new SSHClientManager([], this.MAX_TRIAL_NUMBER_PER_SSHCONNECTION, rmMeta);
            const sshClient: Client = await sshClientManager.getAvailableSSHClient();
SparkSnail's avatar
SparkSnail committed
420
421
422
423
            this.machineSSHClientMap.set(rmMeta, sshClientManager);
            await this.initRemoteMachineOnConnected(rmMeta, sshClient);
            if (++connectedRMNum === rmMetaList.length) {
                deferred.resolve();
424
            }
Deshui Yu's avatar
Deshui Yu committed
425
        });
426

Deshui Yu's avatar
Deshui Yu committed
427
428
429
430
431
        return deferred.promise;
    }

    private async initRemoteMachineOnConnected(rmMeta: RemoteMachineMeta, conn: Client): Promise<void> {
        // Create root working directory after ssh connection is ready
432
        const nniRootDir: string = unixPathJoin(getRemoteTmpDir(this.remoteOS), 'nni');
Deshui Yu's avatar
Deshui Yu committed
433
        await SSHClientUtility.remoteExeCommand(`mkdir -p ${this.remoteExpRootDir}`, conn);
434

435
436
        // the directory to store temp scripts in remote machine
        const remoteGpuScriptCollectorDir: string = this.getRemoteScriptsPath(rmMeta.username);
437
        await SSHClientUtility.remoteExeCommand(`(umask 0 ; mkdir -p ${remoteGpuScriptCollectorDir})`, conn);
Deshui Yu's avatar
Deshui Yu committed
438
        await SSHClientUtility.remoteExeCommand(`chmod 777 ${nniRootDir} ${nniRootDir}/* ${nniRootDir}/scripts/*`, conn);
439

Deshui Yu's avatar
Deshui Yu committed
440
        //Begin to execute gpu_metrics_collection scripts
441
        // tslint:disable-next-line: no-floating-promises
442
443
        const script = getGpuMetricsCollectorBashScriptContent(remoteGpuScriptCollectorDir);
        SSHClientUtility.remoteExeCommand(`bash -c '${script}'`, conn);
444

445
        const disposable: Rx.IDisposable = this.timer.subscribe(
Deshui Yu's avatar
Deshui Yu committed
446
447
            async (tick: number) => {
                const cmdresult: RemoteCommandResult = await SSHClientUtility.remoteExeCommand(
448
                    `tail -n 1 ${unixPathJoin(remoteGpuScriptCollectorDir, 'gpu_metrics')}`, conn);
449
                if (cmdresult !== undefined && cmdresult.stdout !== undefined) {
Deshui Yu's avatar
Deshui Yu committed
450
                    rmMeta.gpuSummary = <GPUSummary>JSON.parse(cmdresult.stdout);
451
452
453
454
                    if (rmMeta.gpuSummary.gpuCount === 0) {
                        this.log.warning(`No GPU found on remote machine ${rmMeta.ip}`);
                        this.timer.unsubscribe(disposable);
                    }
Deshui Yu's avatar
Deshui Yu committed
455
456
457
458
459
460
                }
            }
        );
    }

    private async prepareTrialJob(trialJobId: string): Promise<boolean> {
chicm-ms's avatar
chicm-ms committed
461
        const deferred: Deferred<boolean> = new Deferred<boolean>();
Deshui Yu's avatar
Deshui Yu committed
462

463
        if (this.trialConfig === undefined) {
Deshui Yu's avatar
Deshui Yu committed
464
465
            throw new Error('trial config is not initialized');
        }
466
467
468
        if (this.gpuScheduler === undefined) {
            throw new Error('gpuScheduler is not initialized');
        }
Deshui Yu's avatar
Deshui Yu committed
469
470
471
472
        const trialJobDetail: RemoteMachineTrialJobDetail | undefined = this.trialJobsMap.get(trialJobId);
        if (trialJobDetail === undefined) {
            throw new NNIError(NNIErrorNames.INVALID_JOB_DETAIL, `Invalid job detail information for trial job ${trialJobId}`);
        }
473
474
475
        // If job is not WATIING, Don't prepare and resolve true immediately
        if (trialJobDetail.status !== 'WAITING') {
            deferred.resolve(true);
476

477
478
            return deferred.promise;
        }
Deshui Yu's avatar
Deshui Yu committed
479
        // get an ssh client from scheduler
480
        const rmScheduleResult: RemoteMachineScheduleResult = this.gpuScheduler.scheduleMachine(this.trialConfig.gpuNum, trialJobDetail);
Deshui Yu's avatar
Deshui Yu committed
481
        if (rmScheduleResult.resultType === ScheduleResultType.REQUIRE_EXCEED_TOTAL) {
chicm-ms's avatar
chicm-ms committed
482
            const errorMessage: string = `Required GPU number ${this.trialConfig.gpuNum} is too large, no machine can meet`;
Deshui Yu's avatar
Deshui Yu committed
483
484
485
            this.log.error(errorMessage);
            deferred.reject();
            throw new NNIError(NNIErrorNames.RESOURCE_NOT_AVAILABLE, errorMessage);
486
        } else if (rmScheduleResult.resultType === ScheduleResultType.SUCCEED
Deshui Yu's avatar
Deshui Yu committed
487
            && rmScheduleResult.scheduleInfo !== undefined) {
chicm-ms's avatar
chicm-ms committed
488
            const rmScheduleInfo: RemoteMachineScheduleInfo = rmScheduleResult.scheduleInfo;
489
            const trialWorkingFolder: string = unixPathJoin(this.remoteExpRootDir, 'trials', trialJobId);
SparkSnail's avatar
SparkSnail committed
490
491
492
493

            trialJobDetail.rmMeta = rmScheduleInfo.rmMeta;

            await this.allocateSSHClientForTrial(trialJobDetail);
Deshui Yu's avatar
Deshui Yu committed
494
            await this.launchTrialOnScheduledMachine(
495
                trialJobId, trialWorkingFolder, trialJobDetail.form, rmScheduleInfo);
Deshui Yu's avatar
Deshui Yu committed
496
497
498

            trialJobDetail.status = 'RUNNING';
            trialJobDetail.url = `file://${rmScheduleInfo.rmMeta.ip}:${trialWorkingFolder}`;
499
            trialJobDetail.startTime = Date.now();
Deshui Yu's avatar
Deshui Yu committed
500

501
            this.trialJobsMap.set(trialJobId, trialJobDetail);
Deshui Yu's avatar
Deshui Yu committed
502
            deferred.resolve(true);
503
        } else if (rmScheduleResult.resultType === ScheduleResultType.TMP_NO_AVAILABLE_GPU) {
Deshui Yu's avatar
Deshui Yu committed
504
505
506
            this.log.info(`Right now no available GPU can be allocated for trial ${trialJobId}, will try to schedule later`);
            deferred.resolve(false);
        } else {
507
            deferred.reject(`Invalid schedule resutl type: ${rmScheduleResult.resultType}`);
Deshui Yu's avatar
Deshui Yu committed
508
509
510
511
512
513
514
        }

        return deferred.promise;
    }

    private async launchTrialOnScheduledMachine(trialJobId: string, trialWorkingFolder: string, form: TrialJobApplicationForm,
                                                rmScheduleInfo: RemoteMachineScheduleInfo): Promise<void> {
515
        if (this.trialConfig === undefined) {
Deshui Yu's avatar
Deshui Yu committed
516
517
            throw new Error('trial config is not initialized');
        }
chicm-ms's avatar
chicm-ms committed
518
        const cudaVisibleDevice: string = rmScheduleInfo.cudaVisibleDevice;
SparkSnail's avatar
SparkSnail committed
519
        const sshClient: Client | undefined = this.trialSSHClientMap.get(trialJobId);
520
521
522
523
524
525
        if (sshClient === undefined) {
            assert(false, 'sshClient is undefined.');

            // for lint
            return;
        }
526
527
528
529
530
        const trialJobDetail: RemoteMachineTrialJobDetail | undefined = this.trialJobsMap.get(trialJobId);
        if (trialJobDetail === undefined) {
            throw new Error(`Can not get trial job detail for job: ${trialJobId}`);
        }

Deshui Yu's avatar
Deshui Yu committed
531
532
533
        const trialLocalTempFolder: string = path.join(this.expRootDir, 'trials-local', trialJobId);

        await SSHClientUtility.remoteExeCommand(`mkdir -p ${trialWorkingFolder}`, sshClient);
534
        await SSHClientUtility.remoteExeCommand(`mkdir -p ${unixPathJoin(trialWorkingFolder, '.nni')}`, sshClient);
Deshui Yu's avatar
Deshui Yu committed
535
536
537

        // RemoteMachineRunShellFormat is the run shell format string,
        // See definition in remoteMachineData.ts
SparkSnail's avatar
SparkSnail committed
538
539

        let command: string;
chicm-ms's avatar
chicm-ms committed
540
541
        // Set CUDA_VISIBLE_DEVICES environment variable based on cudaVisibleDevice
        // If no valid cudaVisibleDevice is defined, set CUDA_VISIBLE_DEVICES to empty string to hide GPU device
SparkSnail's avatar
SparkSnail committed
542
543
544
        // If gpuNum is undefined, will not set CUDA_VISIBLE_DEVICES in script
        if (this.trialConfig.gpuNum === undefined) {
            command = this.trialConfig.command;
SparkSnail's avatar
SparkSnail committed
545
        } else {
chicm-ms's avatar
chicm-ms committed
546
547
            if (typeof cudaVisibleDevice === 'string' && cudaVisibleDevice.length > 0) {
                command = `CUDA_VISIBLE_DEVICES=${cudaVisibleDevice} ${this.trialConfig.command}`;
SparkSnail's avatar
SparkSnail committed
548
549
550
            } else {
                command = `CUDA_VISIBLE_DEVICES=" " ${this.trialConfig.command}`;
            }
SparkSnail's avatar
SparkSnail committed
551
        }
552
553
554
        // tslint:disable-next-line: strict-boolean-expressions
        const nniManagerIp: string = this.nniManagerIpConfig ? this.nniManagerIpConfig.nniManagerIp : getIPV4Address();
        if (this.remoteRestServerPort === undefined) {
SparkSnail's avatar
SparkSnail committed
555
556
557
            const restServer: RemoteMachineJobRestServer = component.get(RemoteMachineJobRestServer);
            this.remoteRestServerPort = restServer.clusterRestServerPort;
        }
558
        const version: string = this.versionCheck ? await getVersion() : '';
SparkSnail's avatar
SparkSnail committed
559
560
561
        const runScriptTrialContent: string = String.Format(
            REMOTEMACHINE_TRIAL_COMMAND_FORMAT,
            trialWorkingFolder,
Deshui Yu's avatar
Deshui Yu committed
562
563
            trialWorkingFolder,
            trialJobId,
SparkSnail's avatar
SparkSnail committed
564
            getExperimentId(),
565
            trialJobDetail.form.sequenceId.toString(),
566
            this.isMultiPhase,
567
            unixPathJoin(trialWorkingFolder, '.nni', 'jobpid'),
SparkSnail's avatar
SparkSnail committed
568
569
570
            command,
            nniManagerIp,
            this.remoteRestServerPort,
571
            version,
SparkSnail's avatar
SparkSnail committed
572
            this.logCollection,
573
            unixPathJoin(trialWorkingFolder, '.nni', 'code')
574
        );
Deshui Yu's avatar
Deshui Yu committed
575
576

        //create tmp trial working folder locally.
577
        await execMkdir(path.join(trialLocalTempFolder, '.nni'));
Deshui Yu's avatar
Deshui Yu committed
578

SparkSnail's avatar
SparkSnail committed
579
        //create tmp trial working folder locally.
SparkSnail's avatar
SparkSnail committed
580
        await execCopydir(this.trialConfig.codeDir, trialLocalTempFolder);
chicm-ms's avatar
chicm-ms committed
581
        const installScriptContent: string = CONTAINER_INSTALL_NNI_SHELL_FORMAT;
SparkSnail's avatar
SparkSnail committed
582
583
        // Write NNI installation file to local tmp files
        await fs.promises.writeFile(path.join(trialLocalTempFolder, 'install_nni.sh'), installScriptContent, { encoding: 'utf8' });
584
        // Write file content ( run.sh and parameter.cfg ) to local tmp files
SparkSnail's avatar
SparkSnail committed
585
        await fs.promises.writeFile(path.join(trialLocalTempFolder, 'run.sh'), runScriptTrialContent, { encoding: 'utf8' });
chicm-ms's avatar
chicm-ms committed
586
        await this.writeParameterFile(trialJobId, form.hyperParameters);
Deshui Yu's avatar
Deshui Yu committed
587
        // Copy files in codeDir to remote working directory
SparkSnail's avatar
SparkSnail committed
588
        await SSHClientUtility.copyDirectoryToRemote(trialLocalTempFolder, trialWorkingFolder, sshClient, this.remoteOS);
Deshui Yu's avatar
Deshui Yu committed
589
        // Execute command in remote machine
590
        // tslint:disable-next-line: no-floating-promises
591
        SSHClientUtility.remoteExeCommand(`bash ${unixPathJoin(trialWorkingFolder, 'run.sh')}`, sshClient);
Deshui Yu's avatar
Deshui Yu committed
592
593
594
595
596
597
598
599
600
601
602
603
604
605
    }

    private getRmMetaByHost(host: string): RemoteMachineMeta {
        for (const [rmMeta, client] of this.machineSSHClientMap.entries()) {
            if (rmMeta.ip === host) {
                return rmMeta;
            }
        }
        throw new Error(`Host not found: ${host}`);
    }

    private async updateTrialJobStatus(trialJob: RemoteMachineTrialJobDetail, sshClient: Client): Promise<TrialJobDetail> {
        const deferred: Deferred<TrialJobDetail> = new Deferred<TrialJobDetail>();
        const jobpidPath: string = this.getJobPidPath(trialJob.id);
606
        const trialReturnCodeFilePath: string = unixPathJoin(this.remoteExpRootDir, 'trials', trialJob.id, '.nni', 'code');
Deshui Yu's avatar
Deshui Yu committed
607
608
609
610
611
612
        try {
            const killResult: number = (await SSHClientUtility.remoteExeCommand(`kill -0 \`cat ${jobpidPath}\``, sshClient)).exitCode;
            // if the process of jobpid is not alive any more
            if (killResult !== 0) {
                const trailReturnCode: string = await SSHClientUtility.getRemoteFileContent(trialReturnCodeFilePath, sshClient);
                this.log.debug(`trailjob ${trialJob.id} return code: ${trailReturnCode}`);
613
614
615
                const match: RegExpMatchArray | null = trailReturnCode.trim()
                  .match(/^(\d+)\s+(\d+)$/);
                if (match !== null) {
Deshui Yu's avatar
Deshui Yu committed
616
617
618
619
620
                    const { 1: code, 2: timestamp } = match;
                    // Update trial job's status based on result code
                    if (parseInt(code, 10) === 0) {
                        trialJob.status = 'SUCCEEDED';
                    } else {
621
622
623
624
625
626
                        // isEarlyStopped is never set, mean it's not cancelled by NNI, so if the process's exit code >0, mark it as FAILED
                        if (trialJob.isEarlyStopped === undefined) {
                            trialJob.status = 'FAILED';
                        } else {
                            trialJob.status = getJobCancelStatus(trialJob.isEarlyStopped);
                        }
Deshui Yu's avatar
Deshui Yu committed
627
                    }
628
                    trialJob.endTime = parseInt(timestamp, 10);
SparkSnail's avatar
SparkSnail committed
629
                    this.releaseTrialSSHClient(trialJob);
Deshui Yu's avatar
Deshui Yu committed
630
                }
chicm-ms's avatar
chicm-ms committed
631
                this.log.debug(`trailJob status update: ${trialJob.id}, ${trialJob.status}`);
Deshui Yu's avatar
Deshui Yu committed
632
633
634
635
636
637
638
639
640
641
642
            }
            deferred.resolve(trialJob);
        } catch (error) {
            this.log.error(`Update job status exception, error is ${error.message}`);
            if (error instanceof NNIError && error.name === NNIErrorNames.NOT_FOUND) {
                deferred.resolve(trialJob);
            } else {
                trialJob.status = 'UNKNOWN';
                deferred.resolve(trialJob);
            }
        }
643

Deshui Yu's avatar
Deshui Yu committed
644
645
646
        return deferred.promise;
    }

SparkSnail's avatar
SparkSnail committed
647
    private getRemoteScriptsPath(userName: string): string {
648
        return unixPathJoin(getRemoteTmpDir(this.remoteOS), userName, 'nni', 'scripts');
Deshui Yu's avatar
Deshui Yu committed
649
650
651
    }

    private getHostJobRemoteDir(jobId: string): string {
652
        return unixPathJoin(this.remoteExpRootDir, 'hostjobs', jobId);
Deshui Yu's avatar
Deshui Yu committed
653
654
    }

655
    private getRemoteExperimentRootDir(): string {
656
        return unixPathJoin(getRemoteTmpDir(this.remoteOS), 'nni', 'experiments', getExperimentId());
Deshui Yu's avatar
Deshui Yu committed
657
658
    }

chicm-ms's avatar
chicm-ms committed
659
    public get MetricsEmitter(): EventEmitter {
SparkSnail's avatar
SparkSnail committed
660
661
662
        return this.metricsEmitter;
    }

Deshui Yu's avatar
Deshui Yu committed
663
664
665
666
667
668
    private getJobPidPath(jobId: string): string {
        const trialJobDetail: RemoteMachineTrialJobDetail | undefined = this.trialJobsMap.get(jobId);
        if (trialJobDetail === undefined) {
            throw new NNIError(NNIErrorNames.INVALID_JOB_DETAIL, `Invalid job detail information for trial job ${jobId}`);
        }

chicm-ms's avatar
chicm-ms committed
669
        return unixPathJoin(trialJobDetail.workingDirectory, '.nni', 'jobpid');
Deshui Yu's avatar
Deshui Yu committed
670
    }
chicm-ms's avatar
chicm-ms committed
671

chicm-ms's avatar
chicm-ms committed
672
    private async writeParameterFile(trialJobId: string, hyperParameters: HyperParameters): Promise<void> {
SparkSnail's avatar
SparkSnail committed
673
        const sshClient: Client | undefined = this.trialSSHClientMap.get(trialJobId);
chicm-ms's avatar
chicm-ms committed
674
675
676
677
        if (sshClient === undefined) {
            throw new Error('sshClient is undefined.');
        }

678
        const trialWorkingFolder: string = unixPathJoin(this.remoteExpRootDir, 'trials', trialJobId);
chicm-ms's avatar
chicm-ms committed
679
680
        const trialLocalTempFolder: string = path.join(this.expRootDir, 'trials-local', trialJobId);

681
        const fileName: string = generateParamFileName(hyperParameters);
chicm-ms's avatar
chicm-ms committed
682
683
684
        const localFilepath: string = path.join(trialLocalTempFolder, fileName);
        await fs.promises.writeFile(localFilepath, hyperParameters.value, { encoding: 'utf8' });

685
        await SSHClientUtility.copyFileToRemote(localFilepath, unixPathJoin(trialWorkingFolder, fileName), sshClient);
chicm-ms's avatar
chicm-ms committed
686
    }
Deshui Yu's avatar
Deshui Yu committed
687
688
689
}

export { RemoteMachineTrainingService };