-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathVolumeBulkWriter.java
More file actions
207 lines (176 loc) · 7.61 KB
/
Copy pathVolumeBulkWriter.java
File metadata and controls
207 lines (176 loc) · 7.61 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.milvus.bulkwriter;
import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import io.milvus.bulkwriter.model.UploadFilesResult;
import io.milvus.bulkwriter.request.volume.UploadFilesRequest;
import io.milvus.common.utils.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class VolumeBulkWriter extends LocalBulkWriter {
private static final Logger logger = LoggerFactory.getLogger(VolumeBulkWriter.class);
private final String remotePath;
private final List<List<String>> remoteFiles;
private final VolumeFileManager volumeFileManager;
private final VolumeBulkWriterParam volumeBulkWriterParam;
public VolumeBulkWriter(VolumeBulkWriterParam bulkWriterParam) throws IOException {
super(bulkWriterParam.getCollectionSchema(),
bulkWriterParam.getChunkSize(),
bulkWriterParam.getFileType(),
generatorLocalPath(),
bulkWriterParam.getConfig());
Path path = Paths.get(bulkWriterParam.getRemotePath());
Path remoteDirPath = path.resolve(getUUID());
this.remotePath = remoteDirPath + "/";
this.volumeFileManager = initVolumeFileManagerParams(bulkWriterParam);
this.volumeBulkWriterParam = bulkWriterParam;
this.remoteFiles = Lists.newArrayList();
logger.info("Remote buffer writer initialized, target path: {}", remotePath);
}
private VolumeFileManager initVolumeFileManagerParams(VolumeBulkWriterParam bulkWriterParam) throws IOException {
VolumeFileManagerParam volumeFileManagerParam = VolumeFileManagerParam.newBuilder()
.withCloudEndpoint(bulkWriterParam.getCloudEndpoint()).withApiKey(bulkWriterParam.getApiKey())
.withVolumeName(bulkWriterParam.getVolumeName()).withConnectType(bulkWriterParam.getConnectType())
.build();
return new VolumeFileManager(volumeFileManagerParam);
}
@Override
public void appendRow(JsonObject rowData) throws IOException, InterruptedException {
super.appendRow(rowData);
}
@Override
public void commit(boolean async) throws InterruptedException {
super.commit(async);
}
@Override
protected String getDataPath() {
return remotePath;
}
@Override
public List<List<String>> getBatchFiles() {
return remoteFiles;
}
public UploadFilesResult getVolumeUploadResult() {
return UploadFilesResult.builder()
.volumeName(volumeBulkWriterParam.getVolumeName())
.path(remotePath)
.build();
}
@Override
protected void exit() throws InterruptedException {
super.exit();
// remove the temp folder "bulk_writer"
Path parentPath = Paths.get(localPath).getParent();
if (parentPath.toFile().exists() && isEmptyDirectory(parentPath)) {
try {
Files.delete(parentPath);
logger.info("Delete empty directory: " + parentPath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static boolean isEmptyDirectory(Path directory) {
try {
return !Files.walk(directory, 1, FileVisitOption.FOLLOW_LINKS)
.skip(1) // Skip the root directory itself
.findFirst()
.isPresent();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private void rmLocal(String file) {
try {
Path filePath = Paths.get(file);
filePath.toFile().delete();
Path parentDir = filePath.getParent();
if (parentDir != null && !parentDir.toString().equals(localPath)) {
try {
Files.delete(parentDir);
logger.info("Delete empty directory: " + parentDir);
} catch (IOException ex) {
logger.warn("Failed to delete empty directory: " + parentDir);
}
}
} catch (Exception ex) {
logger.warn("Failed to delete local file: " + file);
}
}
@Override
protected void callBack(List<String> fileList) {
serialImportData(fileList);
}
@Override
public void close() throws Exception {
try {
logger.info("execute remaining actions to prevent loss of memory data or residual empty directories.");
exit();
logger.info(String.format("RemoteBulkWriter done! output remote files: %s", getBatchFiles()));
} finally {
volumeFileManager.shutdownGracefully();
}
}
private void serialImportData(List<String> fileList) {
List<String> remoteFileList = new ArrayList<>();
try {
for (String filePath : fileList) {
String relativeFilePath = filePath.replace(super.getDataPath(), "");
String minioFilePath = getMinioFilePath(remotePath, relativeFilePath);
uploadObject(filePath, minioFilePath);
remoteFileList.add(minioFilePath);
rmLocal(filePath);
}
} catch (Exception e) {
ExceptionUtils.throwUnExpectedException(String.format("Failed to upload files, error: %s", e));
}
logger.info("Successfully upload files: " + fileList);
remoteFiles.add(remoteFileList);
}
private void uploadObject(String filePath, String objectName) throws Exception {
logger.info(String.format("Prepare to upload %s to %s", filePath, objectName));
UploadFilesRequest uploadFilesRequest = UploadFilesRequest.builder()
.sourceFilePath(filePath).targetVolumePath(remotePath)
.build();
volumeFileManager.uploadFilesAsync(uploadFilesRequest).get();
logger.info(String.format("Upload file %s to %s", filePath, objectName));
}
private static String generatorLocalPath() {
Path currentWorkingDirectory = Paths.get("").toAbsolutePath();
Path currentScriptPath = currentWorkingDirectory.resolve("bulk_writer");
return currentScriptPath.toString();
}
private static String getMinioFilePath(String remotePath, String relativeFilePath) {
remotePath = remotePath.startsWith("/") ? remotePath.substring(1) : remotePath;
Path remote = Paths.get(remotePath);
relativeFilePath = relativeFilePath.startsWith("/") ? relativeFilePath.substring(1) : relativeFilePath;
Path relative = Paths.get(relativeFilePath);
Path joinedPath = remote.resolve(relative);
return joinedPath.toString().replace("\\", "/");
}
}