util.ts 6.94 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 { file } from '../../node_modules/@types/tmp';
14
import { GPU_INFO_COLLECTOR_FORMAT_WINDOWS } from './gpuData';
15
16
17

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

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

    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);
46
    }
47
48

    return fileCount;
49
50
51
52
}

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

64
65
66
    return Promise.resolve();
}

67
68
69
70
71
72
73
/**
 * 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
74
        await cpp.exec(`powershell.exe Copy-Item "${source}" -Destination "${destination}" -Recurse`);
75
    } else {
SparkSnail's avatar
SparkSnail committed
76
        await cpp.exec(`cp -r '${source}/.' '${destination}'`);
77
    }
78

79
80
81
    return Promise.resolve();
}

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

93
94
95
96
    return Promise.resolve();
}

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

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

120
121
122
123
124
    return Promise.resolve(cmdresult);
}

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

134
135
136
137
138
    return Promise.resolve();
}

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

148
149
150
151
    return Promise.resolve();
}

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

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

191
192
    return Promise.resolve();
}
193
194
195

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

206
207
208
209
210
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 {
211
    if (process.platform === 'win32') {
212
213
214
        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); });
215
    } else {
216
        cp.exec(getGpuMetricsCollectorBashScriptContent(scriptFolder), { shell: '/bin/bash' });
217
218
    }
}