sshClientUtility.ts 6.93 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
/**
 * 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';

22
import * as assert from 'assert';
Deshui Yu's avatar
Deshui Yu committed
23
24
import * as cpp from 'child-process-promise';
import * as path from 'path';
25
import * as os from 'os';
Deshui Yu's avatar
Deshui Yu committed
26
import { Client, ClientChannel, SFTPWrapper } from 'ssh2';
27
import * as stream from 'stream';
Deshui Yu's avatar
Deshui Yu committed
28
29
import { Deferred } from 'ts-deferred';
import { NNIError, NNIErrorNames } from '../../common/errors';
chicm-ms's avatar
chicm-ms committed
30
import { getLogger, Logger } from '../../common/log';
31
import { uniqueString, getRemoteTmpDir, unixPathJoin } from '../../common/utils';
Deshui Yu's avatar
Deshui Yu committed
32
import { RemoteCommandResult } from './remoteMachineData';
33
import { execRemove, tarAdd } from '../common/util';
Deshui Yu's avatar
Deshui Yu committed
34
35
36
37
38
39
40
41
42
43
44
45
46

/**
 *
 * Utility for frequent operations towards SSH client
 *
 */
export namespace SSHClientUtility {
    /**
     * Copy files and directories in local directory recursively to remote directory
     * @param localDirectory local diretory
     * @param remoteDirectory remote directory
     * @param sshClient SSH client
     */
47
    export async function copyDirectoryToRemote(localDirectory : string, remoteDirectory : string, sshClient : Client, remoteOS: string) : Promise<void> {
Deshui Yu's avatar
Deshui Yu committed
48
        const deferred: Deferred<void> = new Deferred<void>();
49
50
        const tmpTarName: string = `${uniqueString(10)}.tar.gz`;
        const localTarPath: string = path.join(os.tmpdir(), tmpTarName);
51
        const remoteTarPath: string = unixPathJoin(getRemoteTmpDir(remoteOS), tmpTarName);
Deshui Yu's avatar
Deshui Yu committed
52
53

        // Compress files in local directory to experiment root directory
54
        await tarAdd(localTarPath, localDirectory);
Deshui Yu's avatar
Deshui Yu committed
55
        // Copy the compressed file to remoteDirectory and delete it
56
        await copyFileToRemote(localTarPath, remoteTarPath, sshClient);
57
        await execRemove(localTarPath);
Deshui Yu's avatar
Deshui Yu committed
58
        // Decompress the remote compressed file in and delete it
59
60
        await remoteExeCommand(`tar -oxzf ${remoteTarPath} -C ${remoteDirectory}`, sshClient);
        await remoteExeCommand(`rm ${remoteTarPath}`, sshClient);
Deshui Yu's avatar
Deshui Yu committed
61
62
63
64
65
66
67
68
69
70
71
        deferred.resolve();

        return deferred.promise;
    }

    /**
     * Copy local file to remote path
     * @param localFilePath the path of local file
     * @param remoteFilePath the target path in remote machine
     * @param sshClient SSH Client
     */
72
    export function copyFileToRemote(localFilePath : string, remoteFilePath : string, sshClient : Client) : Promise<boolean> {
chicm-ms's avatar
chicm-ms committed
73
74
        const log: Logger = getLogger();
        log.debug(`copyFileToRemote: localFilePath: ${localFilePath}, remoteFilePath: ${remoteFilePath}`);
75
76
        assert(sshClient !== undefined);
        const deferred: Deferred<boolean> = new Deferred<boolean>();
Deshui Yu's avatar
Deshui Yu committed
77
78
        sshClient.sftp((err : Error, sftp : SFTPWrapper) => {
            if (err) {
chicm-ms's avatar
chicm-ms committed
79
                log.error(`copyFileToRemote: ${err.message}, ${localFilePath}, ${remoteFilePath}`);
80
81
82
                deferred.reject(err);

                return;
Deshui Yu's avatar
Deshui Yu committed
83
            }
84
            assert(sftp !== undefined);
Deshui Yu's avatar
Deshui Yu committed
85
86
87
            sftp.fastPut(localFilePath, remoteFilePath, (fastPutErr : Error) => {
                sftp.end();
                if (fastPutErr) {
88
                    deferred.reject(fastPutErr);
Deshui Yu's avatar
Deshui Yu committed
89
                } else {
90
                    deferred.resolve(true);
Deshui Yu's avatar
Deshui Yu committed
91
92
93
94
95
96
97
98
99
100
101
102
103
                }
            });
        });

        return deferred.promise;
    }

    /**
     * Execute command on remote machine
     * @param command the command to execute remotely
     * @param client SSH Client
     */
    export function remoteExeCommand(command : string, client : Client): Promise<RemoteCommandResult> {
chicm-ms's avatar
chicm-ms committed
104
105
        const log: Logger = getLogger();
        log.debug(`remoteExeCommand: command: [${command}]`);
Deshui Yu's avatar
Deshui Yu committed
106
107
108
109
110
111
112
        const deferred : Deferred<RemoteCommandResult> = new Deferred<RemoteCommandResult>();
        let stdout: string = '';
        let stderr: string = '';
        let exitCode : number;

        client.exec(command, (err : Error, channel : ClientChannel) => {
            if (err) {
chicm-ms's avatar
chicm-ms committed
113
                log.error(`remoteExeCommand: ${err.message}`);
Deshui Yu's avatar
Deshui Yu committed
114
                deferred.reject(err);
115
116

                return;
Deshui Yu's avatar
Deshui Yu committed
117
118
            }

119
            channel.on('data', (data : any, dataStderr : any) => {
Deshui Yu's avatar
Deshui Yu committed
120
121
                if (dataStderr) {
                    stderr += data.toString();
122
                } else {
Deshui Yu's avatar
Deshui Yu committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
                    stdout += data.toString();
                }
            }).on('exit', (code, signal) => {
                exitCode = code as number;
                deferred.resolve({
                    stdout : stdout,
                    stderr : stderr,
                    exitCode : exitCode
                });
            });
        });

        return deferred.promise;
    }

    export function getRemoteFileContent(filePath: string, sshClient: Client): Promise<string> {
        const deferred: Deferred<string> = new Deferred<string>();
        sshClient.sftp((err: Error, sftp : SFTPWrapper) => {
            if (err) {
142
                getLogger().error(`getRemoteFileContent: ${err.message}`);
Deshui Yu's avatar
Deshui Yu committed
143
                deferred.reject(new Error(`SFTP error: ${err.message}`));
144
145

                return;
Deshui Yu's avatar
Deshui Yu committed
146
147
148
149
150
151
152
153
            }
            try {
                const sftpStream : stream.Readable = sftp.createReadStream(filePath);

                let dataBuffer: string = '';
                sftpStream.on('data', (data : Buffer | string) => {
                    dataBuffer += data;
                }).on('error', (streamErr: Error) => {
154
                    sftp.end();
Deshui Yu's avatar
Deshui Yu committed
155
156
                    deferred.reject(new NNIError(NNIErrorNames.NOT_FOUND, streamErr.message));
                }).on('end', () => {
157
158
                    // sftp connection need to be released manually once operation is done
                    sftp.end();
Deshui Yu's avatar
Deshui Yu committed
159
160
161
                    deferred.resolve(dataBuffer);
                });
            } catch (error) {
162
163
                getLogger().error(`getRemoteFileContent: ${error.message}`);
                sftp.end();
Deshui Yu's avatar
Deshui Yu committed
164
165
166
167
168
169
170
                deferred.reject(new Error(`SFTP error: ${error.message}`));
            }
        });

        return deferred.promise;
    }
}