remoteMachineData.ts 9.26 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
/**
 * 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 { JobApplicationForm, TrialJobDetail, TrialJobStatus  } from '../../common/trainingService';
import { GPUSummary } from '../common/gpuData';
SparkSnail's avatar
SparkSnail committed
24
25
26
import { Client, ConnectConfig } from 'ssh2';
import { Deferred } from 'ts-deferred';
import * as fs from 'fs';
Deshui Yu's avatar
Deshui Yu committed
27
28
29
30
31
32
33
34
35


/**
 * Metadata of remote machine for configuration and statuc query
 */
export class RemoteMachineMeta {
    public readonly ip : string;
    public readonly port : number;
    public readonly username : string;
36
37
38
    public readonly passwd?: string;
    public readonly sshKeyPath?: string;
    public readonly passphrase?: string;
Deshui Yu's avatar
Deshui Yu committed
39
40
41
42
    public gpuSummary : GPUSummary | undefined;
    /* GPU Reservation info, the key is GPU index, the value is the job id which reserves this GPU*/
    public gpuReservation : Map<number, string>;

43
44
    constructor(ip : string, port : number, username : string, passwd : string, 
        sshKeyPath : string, passphrase : string) {
Deshui Yu's avatar
Deshui Yu committed
45
46
47
48
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.passwd = passwd;
49
50
        this.sshKeyPath = sshKeyPath;
        this.passphrase = passphrase;
Deshui Yu's avatar
Deshui Yu committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
        this.gpuReservation = new Map<number, string>();
    }
}

/**
 * The execution result for command executed on remote machine
 */
export class RemoteCommandResult {
    public readonly stdout : string;
    public readonly stderr : string;
    public readonly exitCode : number;

    constructor(stdout : string, stderr : string, exitCode : number) {
        this.stdout = stdout;
        this.stderr = stderr;
        this.exitCode = exitCode;
    }
}

/**
 * RemoteMachineTrialJobDetail
 */
// tslint:disable-next-line:max-classes-per-file
export class RemoteMachineTrialJobDetail implements TrialJobDetail {
    public id: string;
    public status: TrialJobStatus;
77
78
79
    public submitTime: number;
    public startTime?: number;
    public endTime?: number;
Deshui Yu's avatar
Deshui Yu committed
80
81
82
83
    public tags?: string[];
    public url?: string;
    public workingDirectory: string;
    public form: JobApplicationForm;
84
    public sequenceId: number;
Deshui Yu's avatar
Deshui Yu committed
85
    public rmMeta?: RemoteMachineMeta;
86
    public isEarlyStopped?: boolean;
Deshui Yu's avatar
Deshui Yu committed
87

88
89
    constructor(id: string, status: TrialJobStatus, submitTime: number,
                workingDirectory: string, form: JobApplicationForm, sequenceId: number) {
Deshui Yu's avatar
Deshui Yu committed
90
91
92
93
94
        this.id = id;
        this.status = status;
        this.submitTime = submitTime;
        this.workingDirectory = workingDirectory;
        this.form = form;
95
        this.sequenceId = sequenceId;
Deshui Yu's avatar
Deshui Yu committed
96
97
98
99
        this.tags = [];
    }
}

SparkSnail's avatar
SparkSnail committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/**
 * The remote machine ssh client used for trial and gpu detector
 */
export class SSHClient {
    private readonly sshClient: Client;
    private usedConnectionNumber: number; //count the connection number of every client
    constructor(sshClient: Client, usedConnectionNumber: number) {
        this.sshClient = sshClient;
        this.usedConnectionNumber = usedConnectionNumber;
    }
    
    public get getSSHClientInstance(): Client {
        return this.sshClient;
    }

    public get getUsedConnectionNumber(): number {
        return this.usedConnectionNumber;
    }

    public addUsedConnectionNumber() {
        this.usedConnectionNumber += 1;
    }

    public minusUsedConnectionNumber() {
        this.usedConnectionNumber -= 1;
    }
}

export class SSHClientManager {
    private sshClientArray: SSHClient[];
    private readonly maxTrialNumberPerConnection: number;
    private readonly rmMeta: RemoteMachineMeta;
    constructor(sshClientArray: SSHClient[], maxTrialNumberPerConnection: number, rmMeta: RemoteMachineMeta) {
        this.rmMeta = rmMeta;
        this.sshClientArray = sshClientArray;
        this.maxTrialNumberPerConnection = maxTrialNumberPerConnection;
    }

    /**
     * Create a new ssh connection client and initialize it
     */
    private initNewSSHClient(): Promise<Client> {
        const deferred: Deferred<Client> = new Deferred<Client>();
        const conn: Client = new Client();
        let connectConfig: ConnectConfig = {
            host: this.rmMeta.ip,
            port: this.rmMeta.port,
            username: this.rmMeta.username };
        if (this.rmMeta.passwd) {
            connectConfig.password = this.rmMeta.passwd;                
        } else if(this.rmMeta.sshKeyPath) {
            if(!fs.existsSync(this.rmMeta.sshKeyPath)) {
                //SSh key path is not a valid file, reject
                deferred.reject(new Error(`${this.rmMeta.sshKeyPath} does not exist.`));
            }
            const privateKey: string = fs.readFileSync(this.rmMeta.sshKeyPath, 'utf8');

            connectConfig.privateKey = privateKey;
            connectConfig.passphrase = this.rmMeta.passphrase;
        } else {
            deferred.reject(new Error(`No valid passwd or sshKeyPath is configed.`));
        }
        conn.on('ready', () => {
            this.addNewSSHClient(conn);
            deferred.resolve(conn);
        }).on('error', (err: Error) => {
            // SSH connection error, reject with error message
            deferred.reject(new Error(err.message));
        }).connect(connectConfig);
      
        return deferred.promise;
    }
    
    /**
     * find a available ssh client in ssh array, if no ssh client available, return undefined
     */
    public async getAvailableSSHClient(): Promise<Client> {
        const deferred: Deferred<Client> = new Deferred<Client>();
        for (const index in this.sshClientArray) {
            let connectionNumber: number = this.sshClientArray[index].getUsedConnectionNumber;
            if(connectionNumber < this.maxTrialNumberPerConnection) {
                this.sshClientArray[index].addUsedConnectionNumber();
                deferred.resolve(this.sshClientArray[index].getSSHClientInstance);
                return deferred.promise;
            }
        };
        //init a new ssh client if could not get an available one
        return await this.initNewSSHClient();
    }
    
    /**
     * add a new ssh client to sshClientArray
     * @param sshClient
     */
    public addNewSSHClient(client: Client) {
        this.sshClientArray.push(new SSHClient(client, 1));
    }
    
    /**
     * first ssh clilent instance is used for gpu collector and host job
     */
    public getFirstSSHClient() {
        return this.sshClientArray[0].getSSHClientInstance;
    }
    
    /**
     * close all of ssh client
     */
    public closeAllSSHClient() {
        for (let sshClient of this.sshClientArray) {
            sshClient.getSSHClientInstance.end();
        }
    }
    
    /**
     * retrieve resource, minus a number for given ssh client
     * @param client
     */
    public releaseConnection(client: Client | undefined) {
        if(!client) {
            throw new Error(`could not release a undefined ssh client`);
        }
        for(let index in this.sshClientArray) {
            if(this.sshClientArray[index].getSSHClientInstance === client) {
                this.sshClientArray[index].minusUsedConnectionNumber();
                break;
            }
        }
    }
} 


232
export type RemoteMachineScheduleResult = { scheduleInfo : RemoteMachineScheduleInfo | undefined; resultType : ScheduleResultType};
Deshui Yu's avatar
Deshui Yu committed
233

234
export type RemoteMachineScheduleInfo = { rmMeta : RemoteMachineMeta; cuda_visible_device : string};
Deshui Yu's avatar
Deshui Yu committed
235
236
237
238
239
240
241
242
243
244
245
246

export enum ScheduleResultType {
    /* Schedule succeeded*/
    SUCCEED,

    /* Temporarily, no enough available GPU right now */    
    TMP_NO_AVAILABLE_GPU,

    /* Cannot match requirement even if all GPU are a*/
    REQUIRE_EXCEED_TOTAL
}

SparkSnail's avatar
SparkSnail committed
247
export const REMOTEMACHINE_TRIAL_COMMAND_FORMAT: string =
Deshui Yu's avatar
Deshui Yu committed
248
`#!/bin/bash
SparkSnail's avatar
SparkSnail committed
249
export NNI_PLATFORM=remote NNI_SYS_DIR={0} NNI_OUTPUT_DIR={1} NNI_TRIAL_JOB_ID={2} NNI_EXP_ID={3} NNI_TRIAL_SEQ_ID={4} export MULTI_PHASE={5}
Deshui Yu's avatar
Deshui Yu committed
250
cd $NNI_SYS_DIR
SparkSnail's avatar
SparkSnail committed
251
252
sh install_nni.sh
echo $$ >{6}
253
254
python3 -m nni_trial_tool.trial_keeper --trial_command '{7}' --nnimanager_ip '{8}' --nnimanager_port '{9}' --version '{10}' 1>$NNI_OUTPUT_DIR/trialkeeper_stdout 2>$NNI_OUTPUT_DIR/trialkeeper_stderr
echo $? \`date +%s%3N\` >{11}`;
Deshui Yu's avatar
Deshui Yu committed
255

256
export const HOST_JOB_SHELL_FORMAT: string =
Deshui Yu's avatar
Deshui Yu committed
257
258
259
260
261
`#!/bin/bash
cd {0}
echo $$ >{1}
eval {2} >stdout 2>stderr
echo $? \`date +%s%3N\` >{3}`;
SparkSnail's avatar
SparkSnail committed
262
263
264
265
266
267
268
269

export const GPU_COLLECTOR_FORMAT: string = 
`
#!/bin/bash
export METRIC_OUTPUT_DIR={0}
echo $$ >{1}
python3 -m nni_gpu_tool.gpu_metrics_collector
`