Newer
Older
/*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.service;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.persistence.FileDAO;
import it.inaf.ia2.transfer.persistence.LocationDAO;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import it.inaf.oats.vospace.exception.InternalFaultException;
import it.inaf.oats.vospace.exception.PermissionDeniedException;
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
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class FileCopyService {
private static final Logger LOG = LoggerFactory.getLogger(FileCopyService.class);
@Autowired
private FileDAO fileDAO;
@Autowired
private LocationDAO locationDAO;
@Autowired
private AuthorizationService authorizationService;
@Autowired
private RestTemplate restTemplate;
@Value("${upload_location_id}")
private int uploadLocationId;
public void copyFiles(String sourceRootVosPath,
String destinationRootVosPath, String jobId, TokenPrincipal principal) {
// We use jobId to identify nodes created by the REST part of CopyNode
// We expect them to be locked
List<FileInfo> sources
= fileDAO.getBranchFileInfos(sourceRootVosPath, jobId);
// Set location of destinations to this file service update location
// before retrieving file infos
fileDAO.setBranchLocationId(destinationRootVosPath, jobId, uploadLocationId);
List<FileInfo> destinations
= fileDAO.getBranchFileInfos(destinationRootVosPath, jobId);
if (sources.size() != destinations.size()) {
throw new IllegalStateException("Sources and destinations list have different sizes");
}
// Create destination directories on disk
this.makeDirectoryStructure(destinations);
this.fillDestinations(destinations,
sources,
sourceRootVosPath,
destinationRootVosPath,
principal);
}
private void makeDirectory(FileInfo containerFileInfo) {
File file = new File(containerFileInfo.getOsPath());
if (!file.exists()) {
if (!file.mkdirs()) {
throw new IllegalStateException("Unable to create directory " + containerFileInfo.getOsPath());
}
}
}
private void makeDirectoryStructure(List<FileInfo> destinationFileInfos) {
for (FileInfo f : destinationFileInfos) {
if (f.isDirectory()) {
this.makeDirectory(f);
}
}
}
private void fillDestinations(List<FileInfo> destinationFileInfos,
List<FileInfo> sourcesFileInfos,
String sourceRootVosPath,
String destinationRootVosPath,
TokenPrincipal principal) {
// it will be initialized only when necessary
Map<Integer, String> portalLocationUrls = null;
for (FileInfo f : destinationFileInfos) {
if (!f.isDirectory()) {
// Calculate source file vos path
String correspondingSourceVosPath
= this.getCorrespondingSourceVosPath(
sourceRootVosPath,
destinationRootVosPath,
f.getVirtualPath());
Optional<FileInfo> sourceOpt = this.findFileInfoByVosPath(sourcesFileInfos,
correspondingSourceVosPath);
FileInfo source = sourceOpt
.orElseThrow(() -> new IllegalStateException("Can't find file info for: "
+ correspondingSourceVosPath + " in source files list"));
if (source.getLocationId() != null && source.getLocationId() != uploadLocationId) {
// remote file
if (portalLocationUrls == null) {
portalLocationUrls = locationDAO.getPortalLocationUrls();
}
String url = portalLocationUrls.get(source.getLocationId());
// download file to destination disk path
this.downloadFileToDisk(source, f, principal, url);
} else {
// local file
// copy file to destination disk path
this.copyLocalFile(source, f, principal);
}
}
}
}
private String getCorrespondingSourceVosPath(String sourceRootVosPath,
String destinationRootVosPath,
String destinationVosPath) {
return sourceRootVosPath
+ destinationVosPath.substring(destinationRootVosPath.length());
}
private Optional<FileInfo> findFileInfoByVosPath(List<FileInfo> list, String vosPath) {
return list.stream().filter(i -> i.getVirtualPath().equals(vosPath)).findFirst();
}
private void downloadFileToDisk(FileInfo sourceFile,
FileInfo destinationFile, TokenPrincipal tokenPrincipal, String baseUrl) {
if (baseUrl == null) {
LOG.error("Location URL not found for location " + sourceFile.getLocationId());
throw new InternalFaultException("Unable to retrieve location of file " + sourceFile.getVirtualPath());
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
}
String url = baseUrl + "/" + sourceFile.getVirtualName();
LOG.trace("Downloading file from " + url);
restTemplate.execute(url, HttpMethod.GET, req -> {
HttpHeaders headers = req.getHeaders();
if (tokenPrincipal.getToken() != null) {
headers.setBearerAuth(tokenPrincipal.getToken());
}
}, res -> {
File outFile = new File(destinationFile.getOsPath());
try (FileOutputStream os = new FileOutputStream(outFile)) {
res.getBody().transferTo(os);
} catch (Exception e) {
outFile.delete();
throw e;
}
return null;
}, new Object[]{});
}
private void copyLocalFile(FileInfo sourceFileInfo,
FileInfo destinationFileInfo, TokenPrincipal tokenPrincipal) {
if (!authorizationService.isDownloadable(sourceFileInfo, tokenPrincipal)) {
throw PermissionDeniedException.forPath(sourceFileInfo.getVirtualPath());
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
}
File file = new File(sourceFileInfo.getOsPath());
LOG.trace("Copying file: " + file.getAbsolutePath() + " to: "
+ destinationFileInfo.getOsPath());
File sourceFile = new File(sourceFileInfo.getOsPath());
File destinationFile = new File(destinationFileInfo.getOsPath());
try {
Files.copy(sourceFile.toPath(), destinationFile.toPath());
} catch (IOException e) {
if (Files.exists(destinationFile.toPath())) {
destinationFile.delete();
}
throw new UncheckedIOException(e);
} catch (Exception e) {
if (Files.exists(destinationFile.toPath())) {
destinationFile.delete();
}
throw e;
}
}
}