azureStorageClientUtils.ts 8.44 KB
Newer Older
SparkSnail's avatar
SparkSnail committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * 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 * as fs from 'fs'
import * as path from 'path';
import { Deferred } from 'ts-deferred';
import { getLogger } from '../../common/log';
import { mkDirP } from '../../common/utils';

export namespace AzureStorageClientUtility {
29

SparkSnail's avatar
SparkSnail committed
30
31
    /**
     * create azure share
32
33
     * @param fileServerClient
     * @param azureShare
SparkSnail's avatar
SparkSnail committed
34
35
36
37
38
39
40
41
42
43
44
45
46
     */
    export async function createShare(fileServerClient: any, azureShare: any): Promise<void>{
        const deferred: Deferred<void> = new Deferred<void>();
        fileServerClient.createShareIfNotExists(azureShare, function(error: any, result: any, response: any) {
            if(error){
                getLogger().error(`Create share failed:, ${error}`);
                deferred.reject(error)
            }else{
                deferred.resolve()
            }
        })
        return deferred.promise;
    }
47

SparkSnail's avatar
SparkSnail committed
48
49
    /**
     * Create a new directory (NOT recursively) in azure file storage.
50
51
52
     * @param fileServerClient
     * @param azureFoler
     * @param azureShare
SparkSnail's avatar
SparkSnail committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
     */
    export async function createDirectory(fileServerClient: any, azureFoler: any, azureShare: any): Promise<void>{
        const deferred: Deferred<void> = new Deferred<void>();
        fileServerClient.createDirectoryIfNotExists(azureShare, azureFoler, function(error: any, result: any, response: any) {
            if(error){
                getLogger().error(`Create directory failed:, ${error}`);
                deferred.reject(error);
            }else{
                deferred.resolve();
            }
        })
        return deferred.promise;
    }

    /**
     * Create a new directory recursively in azure file storage
     * @param fileServerClient
70
     * @param azureDirectory
SparkSnail's avatar
SparkSnail committed
71
72
73
74
75
76
77
78
79
80
81
82
83
     */
    export async function createDirectoryRecursive(fileServerClient: any, azureDirectory: any, azureShare: any): Promise<void>{
        const deferred: Deferred<void> = new Deferred<void>();
        let directories = azureDirectory.split("/");
        let rootDirectory = ""
        for(let directory of directories){
            rootDirectory += directory;
            await createDirectory(fileServerClient, rootDirectory, azureShare);
            rootDirectory += '/';
        }
        deferred.resolve();
        return deferred.promise;
    }
84

SparkSnail's avatar
SparkSnail committed
85
86
    /**
     * upload a file to azure storage
87
88
89
90
91
     * @param fileServerClient
     * @param azureDirectory
     * @param azureFileName
     * @param azureShare
     * @param localFilePath
SparkSnail's avatar
SparkSnail committed
92
93
94
95
96
97
98
     */
    async function uploadFileToAzure(fileServerClient: any, azureDirectory: any, azureFileName: any, azureShare: any, localFilePath: any): Promise<void>{
        const deferred: Deferred<void> = new Deferred<void>();
        await fileServerClient.createFileFromLocalFile(azureShare, azureDirectory, azureFileName, localFilePath, function(error: any, result: any, response: any) {
            if(error){
                getLogger().error(`Upload file failed:, ${error}`);
                deferred.reject(error);
99
            }else{
SparkSnail's avatar
SparkSnail committed
100
101
102
103
104
                deferred.resolve();
            }
        })
        return deferred.promise;
    }
105

SparkSnail's avatar
SparkSnail committed
106
107
    /**
     * download a file from azure storage
108
109
110
111
112
     * @param fileServerClient
     * @param azureDirectory
     * @param azureFileName
     * @param azureShare
     * @param localFilePath
SparkSnail's avatar
SparkSnail committed
113
114
115
116
117
118
119
120
     */
    async function downloadFile(fileServerClient: any, azureDirectory: any, azureFileName: any, azureShare: any, localFilePath: any): Promise<void>{
        const deferred: Deferred<void> = new Deferred<void>();
        await fileServerClient.getFileToStream(azureShare, azureDirectory, azureFileName, fs.createWriteStream(localFilePath), function(error: any, result: any, response: any) {
            if(error){
                getLogger().error(`Download file failed:, ${error}`);
                deferred.reject(error);
            }else{
121
                deferred.resolve();
SparkSnail's avatar
SparkSnail committed
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
            }
        })
        return deferred.promise;
    }

    /**
     * Upload a directory to azure file storage
     * @param fileServerClient : the client of file server
     * @param azureDirectory : the directory in azure file storage
     * @param azureShare : the azure share used
     * @param localDirectory : local directory to be uploaded
     */
    export async function uploadDirectory(fileServerClient: any, azureDirectory: any, azureShare: any, localDirectory: any): Promise<void>{
        const deferred: Deferred<void> = new Deferred<void>();
        const fileNameArray: string[] = fs.readdirSync(localDirectory);
        await createDirectoryRecursive(fileServerClient, azureDirectory, azureShare);
        for(let fileName of fileNameArray){
            const fullFilePath: string = path.join(localDirectory, fileName);
            try {
                if (fs.lstatSync(fullFilePath).isFile()) {
                    await uploadFileToAzure(fileServerClient, azureDirectory, fileName, azureShare, fullFilePath);
                } else {
                    // If filePath is a directory, recuisively copy it to azure
                    await uploadDirectory(fileServerClient, azureDirectory + '/' + fileName, azureShare, fullFilePath);
                }
            } catch(error) {
                deferred.reject(error);
                return deferred.promise;
            }
        }
        // All files/directories are copied successfully, resolve
        deferred.resolve();
        return deferred.promise;
    }
156

SparkSnail's avatar
SparkSnail committed
157
158
    /**
     * downlod a directory from azure
159
160
161
162
     * @param fileServerClient
     * @param azureDirectory
     * @param azureShare
     * @param localDirectory
SparkSnail's avatar
SparkSnail committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
     */
    export async function downloadDirectory(fileServerClient: any, azureDirectory:any, azureShare: any, localDirectory: any): Promise<void>{
        const deferred: Deferred<void> = new Deferred<void>();
        mkDirP(localDirectory);
        fileServerClient.listFilesAndDirectoriesSegmented(azureShare, azureDirectory, 'null', function(error: any, result: any, response: any) {
            if(('entries' in result) === false){
                getLogger().error(`list files failed, can't get entries in result`);
                throw new Error(`list files failed, can't get entries in result`);
            }

            if(('files' in result['entries']) === false){
                getLogger().error(`list files failed, can't get files in result['entries']`);
                throw new Error(`list files failed, can't get files in result['entries']`);
            }

            if(('directories' in result['directories']) === false){
                getLogger().error(`list files failed, can't get directories in result['entries']`);
                throw new Error(`list files failed, can't get directories in result['entries']`);
            }

            for(var fileName of result['entries']['files']){
                const fullFilePath: string = path.join(localDirectory, fileName.name);
                downloadFile(fileServerClient, azureDirectory, fileName.name, azureShare, fullFilePath)
            }
187

SparkSnail's avatar
SparkSnail committed
188
189
190
191
192
193
194
195
196
197
            for(var directoryName of result['entries']['directories']){
                const fullDirectoryPath: string = path.join(localDirectory, directoryName.name)
                const fullAzureDirectory: string = path.join(azureDirectory, directoryName.name)
                downloadDirectory(fileServerClient, fullAzureDirectory, azureShare, fullDirectoryPath)
            }
            deferred.resolve();
        })
        return deferred.promise;
    }
}