summaryrefslogtreecommitdiffstats
path: root/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/fileserv/ActiveUpload.java
blob: e7841ccd5da2bae79c3393c91fbffc251bd20b58 (plain) (blame)
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package org.openslx.bwlp.sat.fileserv;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.log4j.Logger;
import org.openslx.bwlp.sat.database.mappers.DbImage;
import org.openslx.bwlp.sat.util.Configuration;
import org.openslx.bwlp.sat.util.Constants;
import org.openslx.bwlp.sat.util.FileSystem;
import org.openslx.bwlp.sat.util.Formatter;
import org.openslx.bwlp.sat.util.Util;
import org.openslx.bwlp.thrift.iface.ImageDetailsRead;
import org.openslx.bwlp.thrift.iface.ImageVersionWrite;
import org.openslx.bwlp.thrift.iface.TransferState;
import org.openslx.bwlp.thrift.iface.TransferStatus;
import org.openslx.bwlp.thrift.iface.UserInfo;
import org.openslx.filetransfer.DataReceivedCallback;
import org.openslx.filetransfer.Downloader;
import org.openslx.filetransfer.FileRange;
import org.openslx.filetransfer.WantRangeCallback;
import org.openslx.filetransfer.util.ChunkList;
import org.openslx.filetransfer.util.FileChunk;
import org.openslx.filetransfer.util.HashChecker;
import org.openslx.filetransfer.util.HashChecker.HashCheckCallback;
import org.openslx.filetransfer.util.HashChecker.HashResult;

public class ActiveUpload implements HashCheckCallback {

	private static final Logger LOGGER = Logger.getLogger(ActiveUpload.class);

	/**
	 * How many concurrent connections per upload
	 */
	private static final int MAX_CONNECTIONS = Math.max(Constants.MAX_UPLOADS / 4, 1);

	/**
	 * Self reference for inner classes.
	 */
	private final ActiveUpload activeUpload = this;

	/**
	 * This is an active upload, so on our end, we have a Downloader.
	 */
	private List<Downloader> downloads = new ArrayList<>();

	private final File destinationFile;

	private final RandomAccessFile outFile;

	private final ChunkList chunks;

	private final long fileSize;

	/**
	 * User owning this uploaded file.
	 */
	private final UserInfo owner;

	/**
	 * Base image this upload is a new version for.
	 */
	private final ImageDetailsRead image;

	/**
	 * Flags to set for this new image version. Optional field.
	 */
	private ImageVersionWrite versionSettings = null;

	/**
	 * TransferState of this upload
	 */
	private TransferState state = TransferState.IDLE;

	/**
	 * ID of this upload - will become this version id on success.
	 */
	private final String uploadId;

	/**
	 * Description of this VM - binary dump of e.g. the *.vmx file (VMware)
	 */
	private final byte[] machineDescription;

	/**
	 * Indicated whether the version information was written to db already.
	 * Disallow setVersionData in that case.
	 */
	private final AtomicBoolean versionWrittenToDb = new AtomicBoolean();

	/**
	 * Whether file is (still) writable. Used for the file transfer callbacks.
	 */
	private boolean fileWritable = true;

	private static final HashChecker hashChecker;

	static {
		HashChecker hc;
		try {
			hc = new HashChecker("SHA1");
		} catch (NoSuchAlgorithmException e) {
			hc = null;
		}
		hashChecker = hc;
	}

	public ActiveUpload(String uploadId, UserInfo owner, ImageDetailsRead image, File destinationFile,
			long fileSize, List<ByteBuffer> sha1Sums, byte[] machineDescription) throws FileNotFoundException {
		this.destinationFile = destinationFile;
		this.outFile = new RandomAccessFile(destinationFile, "rw");
		this.chunks = new ChunkList(fileSize, sha1Sums);
		this.owner = owner;
		this.image = image;
		this.fileSize = fileSize;
		this.uploadId = uploadId;
		this.machineDescription = machineDescription;
	}

	/**
	 * Set meta data for this image version.
	 * 
	 * @param user
	 * 
	 * @param data
	 */
	public boolean setVersionData(UserInfo user, ImageVersionWrite data) {
		synchronized (versionWrittenToDb) {
			if (versionWrittenToDb.get()) {
				return false;
			}
			if (!user.userId.equals(owner.userId)) {
				return false;
			}
			versionSettings = data;
			return true;
		}
	}

	/**
	 * Add another connection for this file transfer. Currently only one
	 * connection is allowed, but this might change in the future.
	 * 
	 * @param connection
	 * @return true if the connection is accepted, false if it should be
	 *         discarded
	 */
	public synchronized boolean addConnection(final Downloader connection, ThreadPoolExecutor pool) {
		if (chunks.isComplete() || state == TransferState.FINISHED || state == TransferState.ERROR)
			return false;
		synchronized (downloads) {
			if (downloads.size() >= MAX_CONNECTIONS)
				return false;
			downloads.add(connection);
		}
		try {
			pool.execute(new Runnable() {
				@Override
				public void run() {
					CbHandler cbh = new CbHandler();
					if (!connection.download(cbh, cbh)) {
						if (cbh.currentChunk != null) {
							// If the download failed and we have a current chunk, put it back into
							// the queue, so it will be handled again later...
							chunks.markFailed(cbh.currentChunk);
						}
						LOGGER.warn("Download of " + destinationFile.getAbsolutePath() + " failed");
					}
					if (chunks.isComplete()) {
						finishUpload();
					}
				}
			});
			state = TransferState.WORKING;
		} catch (Exception e) {
			LOGGER.warn("threadpool rejected the incoming file transfer", e);
			return false;
		}
		return true;
	}

	/**
	 * Write some data to the local file. Thread safe so we could
	 * have multiple concurrent connections later.
	 * 
	 * @param fileOffset
	 * @param dataLength
	 * @param data
	 * @return
	 */
	private void writeFileData(long fileOffset, int dataLength, byte[] data) {
		if (state != TransferState.WORKING)
			throw new IllegalStateException("Cannot write to file if state != RUNNING");
		synchronized (outFile) {
			try {
				outFile.seek(fileOffset);
				outFile.write(data, 0, dataLength);
			} catch (IOException e) {
				LOGGER.error("Cannot write to '" + destinationFile
						+ "'. Disk full, network storage error, bad permissions, ...?", e);
				fileWritable = false;
			}
		}
	}

	/**
	 * Called when the upload finished.
	 */
	private synchronized void finishUpload() {
		synchronized (outFile) {
			if (state != TransferState.WORKING)
				return;
			Util.safeClose(outFile);
			state = TransferState.FINISHED;
		}
		File file = destinationFile;
		// Ready to go. First step: Rename temp file to something usable
		File destination = new File(file.getParent(), Formatter.vmName(owner, image.imageName));
		// Sanity check: destination should be a sub directory of the vmStorePath
		String relPath = FileSystem.getRelativePath(destination, Configuration.getVmStoreBasePath());
		if (relPath == null) {
			LOGGER.warn(destination.getAbsolutePath() + " is not a subdir of "
					+ Configuration.getVmStoreBasePath().getAbsolutePath());
			state = TransferState.ERROR;
			return;
		}
		if (relPath.length() > 200) {
			LOGGER.error("Generated file name is >200 chars. DB will not like it");
		}

		// Execute rename
		boolean ret = false;
		Exception renameException = null;
		try {
			ret = file.renameTo(destination);
		} catch (Exception e) {
			ret = false;
			renameException = e;
		}
		if (!ret) {
			// Rename failed :-(
			LOGGER.warn(
					"Could not rename '" + file.getAbsolutePath() + "' to '" + destination.getAbsolutePath()
							+ "'", renameException);
			state = TransferState.ERROR;
			return;
		}

		// Now insert meta data into DB
		try {
			synchronized (versionWrittenToDb) {
				DbImage.createImageVersion(image.imageBaseId, uploadId, owner, fileSize, relPath,
						versionSettings, chunks, machineDescription);
				versionWrittenToDb.set(true);
			}
		} catch (SQLException e) {
			LOGGER.error("Error finishing upload: Inserting version to DB failed", e);
			state = TransferState.ERROR;
			return;
		}
	}

	public synchronized void cancel() {
		synchronized (downloads) {
			for (Downloader download : downloads) {
				download.cancel();
			}
		}
		if (state != TransferState.FINISHED) {
			state = TransferState.ERROR;
		}
	}

	/**
	 * Get user owning this upload. Can be null in special cases.
	 * 
	 * @return instance of UserInfo for the according user.
	 */
	public UserInfo getOwner() {
		return this.owner;
	}

	public synchronized boolean isComplete() {
		return state == TransferState.FINISHED;
	}

	public File getDestinationFile() {
		return this.destinationFile;
	}

	public long getSize() {
		return this.fileSize;
	}

	/**
	 * Callback class for an instance of the Downloader, which supplies
	 * the Downloader with wanted file ranges, and handles incoming data.
	 */
	private class CbHandler implements WantRangeCallback, DataReceivedCallback {
		/**
		 * The current chunk being transfered.
		 */
		private FileChunk currentChunk = null;
		private byte[] buffer = new byte[FileChunk.CHUNK_SIZE];

		@Override
		public boolean dataReceived(long fileOffset, int dataLength, byte[] data) {
			if (currentChunk == null)
				throw new IllegalStateException("dataReceived without current chunk");
			if (!currentChunk.range.contains(fileOffset, fileOffset + dataLength))
				throw new IllegalStateException("dataReceived with file data out of range");
			System.arraycopy(data, 0, buffer, (int) (fileOffset - currentChunk.range.startOffset), dataLength);
			return fileWritable;
		}

		@Override
		public FileRange get() {
			if (currentChunk != null) {
				if (currentChunk.hasSha1Sum() && hashChecker != null) {
					try {
						hashChecker.queue(currentChunk, buffer, activeUpload);
					} catch (InterruptedException e) {
						Thread.currentThread().interrupt();
						return null;
					}
				} else {
					chunks.markSuccessful(currentChunk);
				}
			}
			// Get next missing chunk
			try {
				currentChunk = chunks.getMissing();
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				return null;
			}
			LOGGER.info("Next missing chunk: " + currentChunk);
			if (currentChunk == null) {
				return null; // No more chunks, returning null tells the Downloader we're done.
			}
			return currentChunk.range;
		}
	}

	public synchronized TransferStatus getStatus() {
		return new TransferStatus(chunks.getStatusArray(), state);
	}

	public String getId() {
		return uploadId;
	}

	@Override
	public void hashCheckDone(HashResult result, byte[] data, FileChunk chunk) {
		switch (result) {
		case FAILURE:
			LOGGER.warn("Hash check of chunk " + chunk.toString() + " failed. Assuming valid.");
			// Fall through
		case VALID:
			writeFileData(chunk.range.startOffset, chunk.range.getLength(), data);
			chunks.markSuccessful(chunk);
			break;
		case INVALID:
			chunks.markFailed(chunk);
		}
	}

	// TODO: Clean up old stale uploads

}