util.ts 6.85 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
3
4
5

'use strict';

6
7
import * as cpp from 'child-process-promise';
import * as cp from 'child_process';
8
import * as fs from 'fs';
9
import * as os from 'os';
10
11
import * as path from 'path';
import { String } from 'typescript-string-operations';
12
import { countFilesRecursively, getNewLine, validateFileNameRecursively } from '../../common/utils';
13
import { GPU_INFO_COLLECTOR_FORMAT_WINDOWS } from './gpuData';
14
15
16

/**
 * Validate codeDir, calculate file count recursively under codeDir, and throw error if any rule is broken
17
 *
18
19
20
 * @param codeDir codeDir in nni config file
 * @returns file number under codeDir
 */
chicm-ms's avatar
chicm-ms committed
21
export async function validateCodeDir(codeDir: string): Promise<number> {
22
    let fileCount: number | undefined;
23
    let fileNameValid: boolean = true;
24
25
    try {
        fileCount = await countFilesRecursively(codeDir);
26
    } catch (error) {
27
28
        throw new Error(`Call count file error: ${error}`);
    }
29
30
    try {
        fileNameValid = await validateFileNameRecursively(codeDir);
31
    } catch (error) {
32
33
        throw new Error(`Validate file name error: ${error}`);
    }
34

35
    if (fileCount !== undefined && fileCount > 1000) {
36
        const errMessage: string = `Too many files(${fileCount} found}) in ${codeDir},`
37
                                    + ` please check if it's a valid code dir`;
38
        throw new Error(errMessage);
39
    }
40
41
42
43

    if (!fileNameValid) {
        const errMessage: string = `File name in ${codeDir} is not valid, please check file names, only support digit number、alphabet and (.-_) in file name.`;
        throw new Error(errMessage);
44
    }
45
46

    return fileCount;
47
48
49
50
}

/**
 * crete a new directory
51
 * @param directory
52
 */
53
export async function execMkdir(directory: string, share: boolean = false): Promise<void> {
54
    if (process.platform === 'win32') {
SparkSnail's avatar
SparkSnail committed
55
        await cpp.exec(`powershell.exe New-Item -Path "${directory}" -ItemType "directory" -Force`);
56
    } else if (share) {
SparkSnail's avatar
SparkSnail committed
57
        await cpp.exec(`(umask 0; mkdir -p '${directory}')`);
58
    } else {
SparkSnail's avatar
SparkSnail committed
59
        await cpp.exec(`mkdir -p '${directory}'`);
60
    }
61

62
63
64
    return Promise.resolve();
}

65
66
67
68
69
70
71
/**
 * copy files to the directory
 * @param source
 * @param destination
 */
export async function execCopydir(source: string, destination: string): Promise<void> {
    if (process.platform === 'win32') {
SparkSnail's avatar
SparkSnail committed
72
        await cpp.exec(`powershell.exe Copy-Item "${source}" -Destination "${destination}" -Recurse`);
73
    } else {
SparkSnail's avatar
SparkSnail committed
74
        await cpp.exec(`cp -r '${source}/.' '${destination}'`);
75
    }
76

77
78
79
    return Promise.resolve();
}

80
81
/**
 * crete a new file
82
 * @param filename
83
84
85
 */
export async function execNewFile(filename: string): Promise<void> {
    if (process.platform === 'win32') {
SparkSnail's avatar
SparkSnail committed
86
        await cpp.exec(`powershell.exe New-Item -Path "${filename}" -ItemType "file" -Force`);
87
    } else {
SparkSnail's avatar
SparkSnail committed
88
        await cpp.exec(`touch '${filename}'`);
89
    }
90

91
92
93
94
    return Promise.resolve();
}

/**
95
 * run script using powershell or bash
96
97
 * @param filePath
 */
98
export function runScript(filePath: string): cp.ChildProcess {
99
    if (process.platform === 'win32') {
SparkSnail's avatar
SparkSnail committed
100
        return cp.exec(`powershell.exe -ExecutionPolicy Bypass -file "${filePath}"`);
101
    } else {
SparkSnail's avatar
SparkSnail committed
102
        return cp.exec(`bash '${filePath}'`);
103
104
105
106
107
    }
}

/**
 * output the last line of a file
108
 * @param filePath
109
110
111
112
 */
export async function execTail(filePath: string): Promise<cpp.childProcessPromise.Result> {
    let cmdresult: cpp.childProcessPromise.Result;
    if (process.platform === 'win32') {
SparkSnail's avatar
SparkSnail committed
113
        cmdresult = await cpp.exec(`powershell.exe Get-Content "${filePath}" -Tail 1`);
114
    } else {
SparkSnail's avatar
SparkSnail committed
115
        cmdresult = await cpp.exec(`tail -n 1 '${filePath}'`);
116
    }
117

118
119
120
121
122
    return Promise.resolve(cmdresult);
}

/**
 * delete a directory
123
 * @param directory
124
 */
125
export async function execRemove(directory: string): Promise<void> {
126
    if (process.platform === 'win32') {
SparkSnail's avatar
SparkSnail committed
127
        await cpp.exec(`powershell.exe Remove-Item "${directory}" -Recurse -Force`);
128
    } else {
SparkSnail's avatar
SparkSnail committed
129
        await cpp.exec(`rm -rf '${directory}'`);
130
    }
131

132
133
134
135
136
    return Promise.resolve();
}

/**
 * kill a process
137
 * @param directory
138
 */
139
export async function execKill(pid: string): Promise<void> {
140
    if (process.platform === 'win32') {
Yuge Zhang's avatar
Yuge Zhang committed
141
        await cpp.exec(`cmd.exe /c taskkill /PID ${pid} /T /F`);
142
143
144
    } else {
        await cpp.exec(`pkill -P ${pid}`);
    }
145

146
147
148
149
    return Promise.resolve();
}

/**
150
 * get command of setting environment variable
151
 * @param  variable
152
 * @returns command string
153
 */
154
export function setEnvironmentVariable(variable: { key: string; value: string }): string {
155
156
    if (process.platform === 'win32') {
        return `$env:${variable.key}="${variable.value}"`;
157
    } else {
SparkSnail's avatar
SparkSnail committed
158
        return `export ${variable.key}='${variable.value}'`;
159
160
161
    }
}

162
163
/**
 * Compress files in directory to tar file
164
165
 * @param  sourcePath
 * @param  tarPath
166
 */
167
export async function tarAdd(tarPath: string, sourcePath: string): Promise<void> {
168
    if (process.platform === 'win32') {
169
170
171
172
173
        const tarFilePath: string = tarPath.split('\\')
                                    .join('\\\\');
        const sourceFilePath: string = sourcePath.split('\\')
                                   .join('\\\\');
        const script: string[] = [];
174
175
176
        script.push(
            `import os`,
            `import tarfile`,
177
            String.Format(`tar = tarfile.open("{0}","w:gz")\r\nfor root,dir,files in os.walk("{1}"):`, tarFilePath, sourceFilePath),
178
179
180
181
182
183
184
185
            `    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 {
186
        await cpp.exec(`tar -czf ${tarPath} -C ${sourcePath} .`);
187
    }
188

189
190
    return Promise.resolve();
}
191
192
193

/**
 * generate script file name
194
 * @param fileNamePrefix
195
196
197
 */
export function getScriptName(fileNamePrefix: string): string {
    if (process.platform === 'win32') {
198
        return String.Format('{0}.ps1', fileNamePrefix);
199
    } else {
200
        return String.Format('{0}.sh', fileNamePrefix);
201
202
203
    }
}

204
205
206
207
208
export function getGpuMetricsCollectorBashScriptContent(scriptFolder: string): string {
    return `echo $$ > ${scriptFolder}/pid ; METRIC_OUTPUT_DIR=${scriptFolder} python3 -m nni_gpu_tool.gpu_metrics_collector`;
}

export function runGpuMetricsCollector(scriptFolder: string): void {
209
    if (process.platform === 'win32') {
210
211
212
        const scriptPath = path.join(scriptFolder, 'gpu_metrics_collector.ps1');
        const content = String.Format(GPU_INFO_COLLECTOR_FORMAT_WINDOWS, scriptFolder, path.join(scriptFolder, 'pid'));
        fs.writeFile(scriptPath, content, { encoding: 'utf8' }, () => { runScript(scriptPath); });
213
    } else {
214
        cp.exec(getGpuMetricsCollectorBashScriptContent(scriptFolder), { shell: '/bin/bash' });
215
216
    }
}