summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/filetransfer/UploadTask.java
blob: f7f5fca704dc2161bea54a4a9a2e635fb3fad4c9 (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
package org.openslx.dozmod.filetransfer;

import java.io.File;
import java.io.FileNotFoundException;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.openslx.bwlp.thrift.iface.TInvalidTokenException;
import org.openslx.bwlp.thrift.iface.TransferState;
import org.openslx.bwlp.thrift.iface.TransferStatus;
import org.openslx.dozmod.Config;
import org.openslx.filetransfer.Transfer;
import org.openslx.filetransfer.UploadStatusCallback;
import org.openslx.filetransfer.Uploader;
import org.openslx.thrifthelper.ThriftManager;

/**
 * Executes the file upload in a background thread and updates progress to
 * listeners.
 */
public class UploadTask extends TransferTask {

	/**
	 * Logger instance for this class.
	 */
	private final static Logger LOGGER = Logger.getLogger(UploadTask.class);
	/**
	 * Update interval of the block progress (needs thrift call to sat)
	 */
	private static final double THRIFT_INTERVAL_SECONDS = 1.7;
	private static final int THRIFT_INTERVAL_MS = (int) (THRIFT_INTERVAL_SECONDS * 1000);

	private final String host;
	private final int port;
	private final String uploadToken;

	public UploadTask(String host, int port, String uploadToken, File uploadFile)
			throws FileNotFoundException {
		super(uploadFile, uploadFile.length());
		if (!uploadFile.canRead())
			throw new FileNotFoundException();
		// TODO: SSL
		this.host = host;
		this.port = port;
		this.uploadToken = uploadToken;
	}

	private class UploadThread extends TransferThread {
		//		private long totalBytesRead = 0;
		private long currentSpeed = 0;
		private Uploader uploader = null;

		@Override
		public void run() {
			try {
				uploader = new Uploader(host, port, Config.TRANSFER_TIMEOUT, null, uploadToken);
			} catch (Exception e) {
				LOGGER.warn("Could not initialize new uploader", e);
				consecutiveInitFails.incrementAndGet();
				connectFailed(this);
				return;
			} // TODO: SSL
			connectSucceeded(this);
			final UploadThread thread = this;

			final boolean ret = uploader.upload(localFile.getAbsolutePath(), new UploadStatusCallback() {
				// progress counter
				private long currentBytes = 0;
				private long lastUpdate = 0;
				private long lastBytes = 0;

				@Override
				public void uploadProgress(long bytesSent) {
					currentBytes += bytesSent;
					final long now = System.currentTimeMillis();
					if (lastUpdate + UPDATE_INTERVAL_MS < now) {
						synchronized (thread) {
							// Calculate updated speed
							// totalBytesRead += currentBytes;
							lastBytes = (lastBytes * 2 + currentBytes) / 3;
							currentSpeed = (1000 * lastBytes) / (now - lastUpdate);
							lastUpdate = now;
						}
						// Reset counters
						currentBytes = 0;
					}
				}

				@Override
				public void uploadError(String message) {
					fireErrorMessage(message);
				}
			});
			if (ret) {
				consecutiveInitFails.set(0);
			} else {
				consecutiveInitFails.incrementAndGet();
			}
			transferEnded(this, ret);
		}

		@Override
		public long getCurrentSpeed() {
			synchronized (this) {
				return currentSpeed;
			}
		}

		@Override
		protected Transfer getTransfer() {
			return uploader;
		}
	}

	private long lastThriftUpdate = 0;

	@Override
	protected TransferEvent getTransferEvent() {
		final long now = System.currentTimeMillis();
		TransferState state = null;
		byte[] blocks = null;
		String error = null;
		if (lastThriftUpdate + THRIFT_INTERVAL_MS < now) {
			lastThriftUpdate = now;
			try {
				TransferStatus uploadStatus = ThriftManager.getSatClient().queryUploadStatus(uploadToken);
				state = uploadStatus.getState();
				blocks = uploadStatus.getBlockStatus();
			} catch (TInvalidTokenException e) {
				error = "Upload token unknown!?";
				state = TransferState.ERROR;
			} catch (TException e) {
				error = "Exception quering upload status: " + e.toString();
			}
		}
		long speed = 0;
		long timeRemaining = 0;
		synchronized (transfers) {
			for (TransferThread thread : transfers) {
				speed += thread.getCurrentSpeed();
			}
		}
		// 0 = complete, 1 = missing, 2 = uploading, 3 = queued for copying, 4 = copying
		if (blocks != null) {
			int missing = 0;
			for (byte b : blocks) {
				if (b != 0) {
					missing++;
				}
			}
			final long bytesRemaining = CHUNK_SIZE * (long) missing;
			timeRemaining = (1000 * bytesRemaining) / (speed + 1);
		}
		TransferEvent event = new TransferEvent(state, blocks, speed, timeRemaining, error);
		return event;
	}

	@Override
	protected TransferThread createNewThread() {
		return new UploadThread();
	}
}