summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/gui/wizard/page/ContainerUploadPage.java
blob: b21564a6c24d32cb0601e602c98b8b6186766b74 (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
package org.openslx.dozmod.gui.wizard.page;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.openslx.bwlp.thrift.iface.ImageDetailsRead;
import org.openslx.dozmod.Config;
import org.openslx.dozmod.gui.helper.I18n;
import org.openslx.dozmod.gui.helper.QFileChooser;
import org.openslx.dozmod.gui.helper.TextChangeListener;
import org.openslx.dozmod.gui.wizard.Wizard;
import org.openslx.dozmod.gui.wizard.layout.ContainerUploadPageLayout;
import org.openslx.dozmod.model.ContainerDefinition;
import org.openslx.dozmod.state.UploadWizardState;
import org.openslx.dozmod.thrift.ThriftActions;
import org.openslx.dozmod.thrift.cache.MetaDataCache;
import org.openslx.virtualization.configuration.VirtualizationConfigurationDocker;
import org.openslx.virtualization.configuration.container.ContainerBuildContextMethod;
import org.openslx.virtualization.configuration.container.ContainerMeta;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ContainerUploadPage extends ContainerUploadPageLayout {

	// TODO: Add a Instruction for the new Container-Feature in bwLehrpool.
	// TODO: Add link to instructions for Docker-Intetragtion at https://www.bwlehrpool.de/doku.php

	/**
	 * Version for serialization.
	 */
	private static final long serialVersionUID = 2564301984375080698L;

	private final Logger LOGGER = Logger.getLogger(ContainerUploadPage.class);

	private final UploadWizardState state;
	private final ImageDetailsRead existingImage;
	private ContainerDefinition containerDefinition;

	/**
	 * Page for uploading an Container Image
	 *
	 * @param wizard The wizard dialog in which this page is active.
	 */
	public ContainerUploadPage(Wizard wizard, final UploadWizardState state) {
		super(wizard);
		this.containerDefinition = new ContainerDefinition();
		this.state = state;

		canComeBack = false;
		existingImage = null;

		// HACK set dummy os
		state.selectedOs = MetaDataCache.getOsById(18);

		init();
	}

	// TODO this constructor is currently used in case if user wants do upload a new version.
	// This makes no currently no sens in context of docker container and this is used.
	public ContainerUploadPage(Wizard wizard, UploadWizardState uploadWizardState,
			ImageDetailsRead imageDetailsRead) {
		super(wizard);

		state = uploadWizardState;
		existingImage = imageDetailsRead;

		// TODO fix this!
		containerDefinition = null;

		lblImageName.setEnabled(existingImage == null);
		txtImageName.setEnabled(existingImage == null);
		txtInfoText.setVisible(existingImage == null);

		state.name = imageDetailsRead.imageName;
		state.defaultPermissions = imageDetailsRead.getDefaultPermissions();
		state.description = imageDetailsRead.getDescription();
		state.detectedOs = MetaDataCache.getOsById(imageDetailsRead.getOsId());
		state.selectedOs = MetaDataCache.getOsById(imageDetailsRead.getOsId());
		state.tags = imageDetailsRead.getTags();
		state.defaultPermissions = imageDetailsRead.getUserPermissions();

		state.uuid = imageDetailsRead.getImageBaseId();
		init();
	}

	public ContainerUploadPage(Wizard wizard, UploadWizardState state,
			ContainerDefinition containerDefinition) {
		this(wizard, state);
		this.containerDefinition = containerDefinition;
	}

	private void init() {
		this.txtImageFile.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				browseFile();
			}
		});
		this.btnBrowseForImage.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				browseFile();
			}
		});

		txtImageName.getDocument().addDocumentListener(new TextChangeListener() {
			@Override public void changed() {
				reactOnUserInput();
			}
		});

		tpInput.addChangeListener(new ChangeListener() {
			@Override public void stateChanged(ChangeEvent e) {
				reactOnUserInput();
			}
		});

		txtGitRepo.getDocument().addDocumentListener(new TextChangeListener() {
			@Override public void changed() {
				reactOnUserInput();
			}
		});

		txtContainerImageFile.addMouseListener(new MouseListener() {
			@Override public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() >= 2)
					browseContainerImageFile();
			}

			@Override public void mousePressed(MouseEvent e) {

			}

			@Override public void mouseReleased(MouseEvent e) {

			}

			@Override public void mouseEntered(MouseEvent e) {

			}

			@Override public void mouseExited(MouseEvent e) {

			}
		});

		btnBrowseForImage.requestFocus();
	}

	private void browseContainerImageFile() {
		QFileChooser fc = new QFileChooser(Config.getUploadPath(), false);
		fc.setAcceptAllFileFilterUsed(false);
		fc.addChoosableFileFilter(new ContainerImageFileFiler());

		int action = fc.showOpenDialog(getDialog());
		File file = fc.getSelectedFile();
		if (action != JFileChooser.APPROVE_OPTION || file == null) {
			txtContainerImageFile.setText("");
			return;
		}

		txtContainerImageFile.setText(file.getAbsolutePath());
		LOGGER.info("Tar File selected");
	}

	private void browseFile() {

		QFileChooser fc = new QFileChooser(Config.getUploadPath(), false);
		fc.setAcceptAllFileFilterUsed(false);
		fc.addChoosableFileFilter(new DockerfileFilter());

		int action = fc.showOpenDialog(getDialog());
		File file = fc.getSelectedFile();

		if (action != JFileChooser.APPROVE_OPTION || file == null)
			return;

		txtImageFile.setText(file.getAbsolutePath());

		if (existingImage == null)
			txtImageName.setText(file.getParentFile().getName());
		else
			txtImageName.setText(existingImage.getImageName());

		state.descriptionFile = file;
		// TESTING: Upload also a prematurely created image (tar)
		String imageName = file.getParentFile().getName();
		File imageTarFile = new File(file.getParentFile(), imageName.concat(".tar"));
		if (imageTarFile.exists()) {
			txtContainerImageFile.setText(imageTarFile.getAbsolutePath());
			LOGGER.info("Prebuild Container Image found");
		}

		Config.setUploadPath(file.getParent());
		reactOnUserInput();
	}

	private File getDummyFile() {
		String configDir = Config.getPath();
		File zeroFile = new File(configDir, "ZERO-FILE");
		// create a temp file with dummy content,
		// because vmchooser relies on an existing image after choosing a lecture.
		// TODO change behavior in vmchooser to allow start lectures without images.
		try {
			if (!zeroFile.exists()) {
				zeroFile.createNewFile();
				FileUtils.writeStringToFile(zeroFile, "ZERO\n", "UTF-8");
			}
		} catch (IOException e) {
			e.printStackTrace();
			LOGGER.error("Could not create a dummy file.", e);
		}
		LOGGER.info("Use dummy file");
		return zeroFile;
	}

	private void reactOnUserInput() {
		boolean completed = checkUserInput();
		if (completed)
			setDescription(I18n.PAGE.getString("ContainerUploadPage.Description.ContainerDefFinished"));
		setPageComplete(completed);
	}

	private boolean checkUserInput() {
		ContainerBuildContextMethod method = getBuildContextMethod();

		switch (method) {
		case IMAGE_REPO:
			if (txtImageRepo.getText() == null || txtImageRepo.getText().isEmpty()) {
				setWarningMessage(I18n.PAGE.getString("ContainerUploadPage.Warning.NoImageRepo"));
				return false;
			}
			break;
		case FILE:
			if (txtImageFile.getText() == null || txtImageFile.getText().isEmpty()) {
				setWarningMessage(I18n.PAGE.getString("ContainerUploadPage.Warning.NoReceipt"));
				return false;
			}
			if (! ContainerDefinition.isValidDockerfile(txtImageFile.getText())) {
				setWarningMessage(I18n.PAGE.getString("ContainerUploadPage.Warning.NoValidDockerfiler"));
				return false;
			}
			break;
		case GIT_REPOSITORY:
			if (txtGitRepo.getText() == null || txtGitRepo.getText().isEmpty()) {
				setWarningMessage(I18n.PAGE.getString("ContainerUploadPage.Warning.NoGitRepository"));
				return false;
			}
			break;
		}

		if (txtImageName.getText() == null || txtImageName.getText().isEmpty()) {
			setWarningMessage(I18n.PAGE.getString("ContainerUploadPage.Warning.NoProperName"));
			return false;
		}
		return true;
	}

	private VirtualizationConfigurationDocker createVirtualizationConfig() {

		ContainerMeta containerMeta = containerDefinition.getContainerMeta();
		containerMeta.setBuildContextMethod(getBuildContextMethod().ordinal());
		containerMeta.setImageName(txtImageName.getText());

		File containerImageFile = new File(txtContainerImageFile.getText());
		if (containerImageFile.exists())
			state.diskFile = containerImageFile;
		else
			state.diskFile = getDummyFile();

		switch (containerDefinition.getBuildContextMethod()) {
		case FILE:
			containerDefinition.setContainerRecipe(state.descriptionFile);
			break;
		case IMAGE_REPO:
			containerMeta.setImageRepo(txtImageRepo.getText());
			state.descriptionFile = getDummyFile();
		case GIT_REPOSITORY:
			containerMeta.setBuildContextUrl(txtGitRepo.getText());
			state.descriptionFile = getDummyFile();
			break;
		}
		return containerDefinition.createVirtualizationConfig();
	}

	/**
	 * This function starts the image creation process. It is triggered by the
	 * "Next" button.
	 * <p>
	 * Depending on the state, it will first try to get a UUID for the new image by
	 * calling createImage() of the thrift API. If a UUID is received, it will
	 * request an upload with requestImageVersionUpload(). If granted, it will
	 * finally start a thread for the UploadTask.
	 * <p>
	 * Then a callback to the Gui is executed where we can process the upload state
	 * and give the user feedback about it.
	 */
	@Override protected boolean wantNextOrFinish() {
		state.virtualizationConfig = createVirtualizationConfig();

		// -- create image to get uuid --
		if (existingImage == null) {
			if (state.uuid == null) {
				state.name = txtImageName.getText();
				state.uuid = ThriftActions.createImage(JOptionPane.getFrameForComponent(this), state.name);
				if (state.uuid == null)
					return false;
				txtImageName.setEnabled(false);
				btnBrowseForImage.setEnabled(false);
				txtImageFile.setEnabled(false);
			}
		} else {
			state.uuid = existingImage.getImageBaseId();
			state.name = existingImage.getImageName();
		}
		return true;
	}

	private static class DockerfileFilter extends FileFilter {

		@Override public boolean accept(File f) {

			Pattern p = Pattern.compile("[Dd]ockerfile");
			Matcher m = p.matcher(f.getName());

			boolean accept = false;
			if ((f.isFile() && m.matches()) || f.isDirectory())
				accept = true;
			return accept;
		}

		@Override public String getDescription() {
			return "Dockerfile";
		}
	}

	private static class ContainerImageFileFiler extends FileFilter {

		@Override public boolean accept(File f) {

			boolean accept = false;
			if ((f.isFile() && f.toString().endsWith(".tar")) || f.isDirectory())
				accept = true;
			return accept;
		}

		@Override public String getDescription() {
			return "Container Image (.tar)";
		}
	}
}