util.ts 7.3 KB
Newer Older
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
23
import * as cpp from 'child-process-promise';
import * as cp from 'child_process';
24
import * as fs from 'fs';
25
import * as os from 'os';
26
27
import * as path from 'path';
import { String } from 'typescript-string-operations';
28
29
30
import { countFilesRecursively, getNewLine } from '../../common/utils';
import { file } from '../../node_modules/@types/tmp';
import { GPU_INFO_COLLECTOR_FORMAT_LINUX, GPU_INFO_COLLECTOR_FORMAT_WINDOWS } from './gpuData';
31
32
33

/**
 * Validate codeDir, calculate file count recursively under codeDir, and throw error if any rule is broken
34
 *
35
36
37
 * @param codeDir codeDir in nni config file
 * @returns file number under codeDir
 */
38
// tslint:disable: no-redundant-jsdoc
39
40
41
42
43
export async function validateCodeDir(codeDir: string) : Promise<number> {
    let fileCount: number | undefined;

    try {
        fileCount = await countFilesRecursively(codeDir);
44
    } catch (error) {
45
46
47
        throw new Error(`Call count file error: ${error}`);
    }

48
    if (fileCount !== undefined && fileCount > 1000) {
49
        const errMessage: string = `Too many files(${fileCount} found}) in ${codeDir},`
50
                                    + ` please check if it's a valid code dir`;
51
        throw new Error(errMessage);
52
53
54
    }

    return fileCount;
55
56
57
58
}

/**
 * crete a new directory
59
 * @param directory
60
61
62
63
64
65
66
 */
export async function execMkdir(directory: string): Promise<void> {
    if (process.platform === 'win32') {
        await cpp.exec(`powershell.exe New-Item -Path ${directory} -ItemType "directory" -Force`);
    } else {
        await cpp.exec(`mkdir -p ${directory}`);
    }
67

68
69
70
    return Promise.resolve();
}

71
72
73
74
75
76
77
78
79
80
81
/**
 * copy files to the directory
 * @param source
 * @param destination
 */
export async function execCopydir(source: string, destination: string): Promise<void> {
    if (process.platform === 'win32') {
        await cpp.exec(`powershell.exe Copy-Item ${source} -Destination ${destination} -Recurse`);
    } else {
        await cpp.exec(`cp -r ${source} ${destination}`);
    }
82

83
84
85
    return Promise.resolve();
}

86
87
/**
 * crete a new file
88
 * @param filename
89
90
91
92
93
94
95
 */
export async function execNewFile(filename: string): Promise<void> {
    if (process.platform === 'win32') {
        await cpp.exec(`powershell.exe New-Item -Path ${filename} -ItemType "file" -Force`);
    } else {
        await cpp.exec(`touch ${filename}`);
    }
96

97
98
99
100
    return Promise.resolve();
}

/**
101
 * run script using powershell or bash
102
103
 * @param filePath
 */
104
export function runScript(filePath: string): cp.ChildProcess {
105
    if (process.platform === 'win32') {
106
        return cp.exec(`powershell.exe -ExecutionPolicy Bypass -file ${filePath}`);
107
108
109
110
111
112
113
    } else {
        return cp.exec(`bash ${filePath}`);
    }
}

/**
 * output the last line of a file
114
 * @param filePath
115
116
117
118
119
120
121
122
 */
export async function execTail(filePath: string): Promise<cpp.childProcessPromise.Result> {
    let cmdresult: cpp.childProcessPromise.Result;
    if (process.platform === 'win32') {
        cmdresult = await cpp.exec(`powershell.exe Get-Content ${filePath} -Tail 1`);
    } else {
        cmdresult = await cpp.exec(`tail -n 1 ${filePath}`);
    }
123

124
125
126
127
128
    return Promise.resolve(cmdresult);
}

/**
 * delete a directory
129
 * @param directory
130
 */
131
export async function execRemove(directory: string): Promise<void> {
132
    if (process.platform === 'win32') {
133
        await cpp.exec(`powershell.exe Remove-Item ${directory} -Recurse -Force`);
134
135
136
    } else {
        await cpp.exec(`rm -rf ${directory}`);
    }
137

138
139
140
141
142
    return Promise.resolve();
}

/**
 * kill a process
143
 * @param directory
144
 */
145
export async function execKill(pid: string): Promise<void> {
146
147
148
149
150
    if (process.platform === 'win32') {
        await cpp.exec(`cmd /c taskkill /PID ${pid} /T /F`);
    } else {
        await cpp.exec(`pkill -P ${pid}`);
    }
151

152
153
154
155
    return Promise.resolve();
}

/**
156
 * get command of setting environment variable
157
 * @param  variable
158
 * @returns command string
159
 */
160
export function setEnvironmentVariable(variable: { key: string; value: string }): string {
161
162
    if (process.platform === 'win32') {
        return `$env:${variable.key}="${variable.value}"`;
163
    } else {
164
165
166
167
        return `export ${variable.key}=${variable.value}`;
    }
}

168
169
/**
 * Compress files in directory to tar file
170
171
 * @param  sourcePath
 * @param  tarPath
172
 */
173
export async function tarAdd(tarPath: string, sourcePath: string): Promise<void> {
174
    if (process.platform === 'win32') {
175
176
177
178
179
        const tarFilePath: string = tarPath.split('\\')
                                    .join('\\\\');
        const sourceFilePath: string = sourcePath.split('\\')
                                   .join('\\\\');
        const script: string[] = [];
180
181
182
        script.push(
            `import os`,
            `import tarfile`,
183
            String.Format(`tar = tarfile.open("{0}","w:gz")\r\nfor root,dir,files in os.walk("{1}"):`, tarFilePath, sourceFilePath),
184
185
186
187
188
189
190
191
            `    for file in files:`,
            `        fullpath = os.path.join(root,file)`,
            `        tar.add(fullpath, arcname=file)`,
            `tar.close()`);
        await fs.promises.writeFile(path.join(os.tmpdir(), 'tar.py'), script.join(getNewLine()), { encoding: 'utf8', mode: 0o777 });
        const tarScript: string = path.join(os.tmpdir(), 'tar.py');
        await cpp.exec(`python ${tarScript}`);
    } else {
192
        await cpp.exec(`tar -czf ${tarPath} -C ${sourcePath} .`);
193
    }
194

195
196
    return Promise.resolve();
}
197
198
199

/**
 * generate script file name
200
 * @param fileNamePrefix
201
202
203
 */
export function getScriptName(fileNamePrefix: string): string {
    if (process.platform === 'win32') {
204
        return String.Format('{0}.ps1', fileNamePrefix);
205
    } else {
206
        return String.Format('{0}.sh', fileNamePrefix);
207
208
209
210
211
    }
}

/**
 * generate script file
212
 * @param gpuMetricCollectorScriptFolder
213
214
 */
export function getgpuMetricsCollectorScriptContent(gpuMetricCollectorScriptFolder: string): string {
215
    if (process.platform === 'win32') {
216
217
218
        return String.Format(
            GPU_INFO_COLLECTOR_FORMAT_WINDOWS,
            gpuMetricCollectorScriptFolder,
219
            path.join(gpuMetricCollectorScriptFolder, 'pid')
220
221
222
223
224
        );
    } else {
        return String.Format(
            GPU_INFO_COLLECTOR_FORMAT_LINUX,
            gpuMetricCollectorScriptFolder,
225
            path.join(gpuMetricCollectorScriptFolder, 'pid')
226
227
228
        );
    }
}