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

import java.awt.Window;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.thrift.TException;
import org.openslx.bwlp.thrift.iface.ImageBaseWrite;
import org.openslx.bwlp.thrift.iface.ImageVersionWrite;
import org.openslx.dozmod.gui.Gui;
import org.openslx.dozmod.gui.helper.I18n;
import org.openslx.dozmod.gui.helper.MessageType;
import org.openslx.dozmod.gui.helper.QuitNotification;
import org.openslx.dozmod.gui.helper.UiFeedback;
import org.openslx.dozmod.gui.wizard.page.ContainerUploadPage;
import org.openslx.dozmod.gui.wizard.page.ImageCustomPermissionPage;
import org.openslx.dozmod.gui.wizard.page.ImageMetaDataPage;
import org.openslx.dozmod.gui.wizard.page.ImageOvfConversionPage;
import org.openslx.dozmod.gui.wizard.page.ImageTypePage;
import org.openslx.dozmod.gui.wizard.page.ImageUploadPage;
import org.openslx.dozmod.gui.wizard.page.ImageUploadSummaryPage;
import org.openslx.dozmod.model.ContainerDefinition;
import org.openslx.dozmod.state.UploadWizardState;
import org.openslx.dozmod.thrift.Session;
import org.openslx.dozmod.thrift.ThriftActions;
import org.openslx.dozmod.thrift.ThriftError;
import org.openslx.dozmod.thrift.UploadInitiator;
import org.openslx.dozmod.thrift.UploadInitiator.GotUploadTokenCallback;
import org.openslx.dozmod.thrift.WrappedException;
import org.openslx.sat.thrift.version.Feature;
import org.openslx.thrifthelper.ThriftManager;
import org.openslx.util.QuickTimer;
import org.openslx.util.QuickTimer.Task;
import org.openslx.virtualization.configuration.VirtualizationConfigurationDocker;

public class ImageCreationWizard extends Wizard implements UiFeedback, QuitNotification {

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

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

	private UploadWizardState state = new UploadWizardState();

	private ContainerDefinition containerDefinition = new ContainerDefinition();

	private List<WizardPage> currentPages = new ArrayList<>();

	private boolean baseWritten = false;
	private boolean permissionsWritten = false;

	/**
	 * Wizard for creating or editing an image
	 *
	 * @param parent whether to create new or edit existing image
	 */
	public ImageCreationWizard(Window parent) {
		super(parent);
		state.defaultPermissions = Session.getSatelliteConfig().defaultImagePermissions;

		if (Session.hasFeature(Feature.DOCKER_CONTAINER)) {
			addPage(new ImageTypePage(this));
		} else {
			doVmCreation();
		}
	}

	/**
	 * Adding Pages to the Wizard to create a virtual machine
	 */
	public void doVmCreation() {

		cleanCurrent();
		state.imageUploadPage = new ImageUploadPage(this, state, null);
		currentPages.add(state.imageUploadPage);
		currentPages.add(new ImageMetaDataPage(this, state));
		currentPages.add(new ImageCustomPermissionPage(this, state));
		addPages();

		state.conversionPage = new ImageOvfConversionPage(this, state);
		addOutOfOrderPage(state.conversionPage);
	}

	/**
	 * Adding Pages to the Wizard to define a docker image
	 */
	public void doDockerCreation() {
		cleanCurrent();

		currentPages.add(new ContainerUploadPage(this, state, containerDefinition));
		currentPages.add(new ImageMetaDataPage(this, state, containerDefinition));
		currentPages.add(new ImageCustomPermissionPage(this, state));
		addPages();
	}

	private void addPages() {
		for (WizardPage i : currentPages) {
			addPage(i);
		}
	}

	private void cleanCurrent() {
		if (!currentPages.isEmpty()) {
			removePages(currentPages);
			currentPages = new ArrayList<WizardPage>();
		}
	}

	@Override public String getWindowTitle() {
		return I18n.WIZARD.getString("ImageCreation.Wizard.title");
	}

	@Override public boolean wantFinish() {

		// TODO copy/paste from ContainerUploadPage.wantNextOrFinish()
		// In order for settings for a container to be recorded in the ImageMetaDataPage for the ContainerDefinition,
		// the UploadInitiator was only allowed to be created here.
		// TODO maybe also for VM-Images this is suitable
		if (state.virtualizationConfig instanceof VirtualizationConfigurationDocker) {
			// Create upload initiator that will manage requesting a token, hashing the
			// file, connecting for upload...
			if (state.upload == null) {
				try {
					state.upload = new UploadInitiator(state.uuid, state.diskFile,
							ByteBuffer.wrap(state.virtualizationConfig.getConfigurationAsByteArray()));
				} catch (WrappedException e) {
					ThriftError.showMessage(this, LOGGER, e.exception, e.displayMessage);
					return false;
				} catch (IOException e) {
					Gui.showMessageBox(this,
							I18n.PAGE.getString("ImageUpload.Message.error.uploadInitiatorFailed"),
							MessageType.ERROR, LOGGER, e);
					return false;
				}
			}
			// Start the hash check now
			state.upload.startHashing();
		}

		// since we only started the upload and created a "blank" image entry
		// we can here do all the sanity checks on the fields of UploadWizardState
		// and react accordingly.
		// check state
		if (!isStateValid()) {
			// TODO: Show what went wrong
			Gui.showMessageBox(this, I18n.WIZARD.getString("ImageCreation.Message.error.stateInvalid"),
					MessageType.ERROR, null, null);
			return false;
		}
		// push image base to satellite
		if (!baseWritten) {
			try {
				ThriftActions.updateImageBase(state.uuid, imageBaseWriteFromState());
			} catch (TException e) {
				ThriftError.showMessage(null, LOGGER, e,
						I18n.WIZARD.getString("ImageCreation.Message.error.baseNotWritten"));
				return false;
			}
			baseWritten = true;
		}
		// push permissions to satellite if we have custom permissions
		if (!permissionsWritten) {
			if (state.permissionMap != null && !state.permissionMap.isEmpty()) {
				try {
					ThriftActions.writeImagePermissions(state.uuid, state.permissionMap);
				} catch (TException e) {
					Gui.showMessageBox(this,
							I18n.WIZARD.getString("ImageCreation.Message.error.permissionsNotWritten"),
							MessageType.ERROR, null, null);
					ThriftActions.deleteImageBase(JOptionPane.getFrameForComponent(this), state.uuid);
					return false;
				}
			}
			permissionsWritten = true;
		}

		state.upload.startUpload(new GotUploadTokenCallback() {
			@Override public void fire() {
				// push version data
				try {
					ThriftActions.updateImageVersion(state.upload.getToken(),
							new ImageVersionWrite(state.isRestricted));
				} catch (TException e) {
					if (state.isRestricted) {
						Gui.showMessageBox(null,
								I18n.WIZARD.getString("ImageCreation.Message.error.updateImageVersionFailed"),
								MessageType.WARNING, LOGGER, e);
					}
				}
			}
		});
		return true;
	}

	@Override public WizardPage performFinish() {
		return new ImageUploadSummaryPage(this, state, true);
	}

	/**
	 * Checks the validity of the state
	 *
	 * @return true if we have all the needed information in the state, false
	 * otherwise
	 */
	private boolean isStateValid() {
		// debug purposes
		if (state.name == null || state.name.isEmpty()) {
			LOGGER.error("No name set in state!");
			return false;
		}
		if (state.description == null || state.description.isEmpty()) {
			LOGGER.error("No description set in state!");
			return false;
		}
		if (state.descriptionFile == null) {
			LOGGER.error("No description file set in state!");
			return false;
		} else {
			if (!state.descriptionFile.canRead()) {
				LOGGER.error(state.descriptionFile.getAbsolutePath() + " cannot be read!");
				return false;
			}
		}
		if (state.diskFile == null) {
			LOGGER.error("No disk file set in state!");
			return false;
		} else {
			if (!state.diskFile.canRead()) {
				LOGGER.error(state.diskFile.getAbsolutePath() + " cannot be read!");
				return false;
			}
		}
		if (state.selectedOs == null) {
			LOGGER.error("No OS set in state!");
			return false;
		}
		if (!state.selectedOs.isSetOsId()) {
			LOGGER.error("OS has no id: " + state.selectedOs.toString());
			return false;
		}
		if (state.virtualizationConfig == null) {
			LOGGER.error("No vm meta data set in state!");
			return false;
		}
		if (state.defaultPermissions == null) {
			LOGGER.error("No permissions set in state!");
			return false;
		}
		if (state.shareMode == null) {
			LOGGER.error("No share mode set in state!");
			return false;
		}
		if (state.uuid == null) {
			LOGGER.error("No uuid set in state!");
			return false;
		}
		return true;
	}

	private ImageBaseWrite imageBaseWriteFromState() {
		// build imageBaseWrite
		return new ImageBaseWrite(state.name, state.description, state.selectedOs.getOsId(),
				state.virtualizationConfig.getVirtualizer().getId(), state.isTemplate,
				state.defaultPermissions, state.shareMode);
	}

	@Override protected final void doPrevious() {
		if (outOfOrderPage != null) {
			outOfOrderPage = null;
			returnAfterOutOfOrderPage(state.imageUploadPage, state.conversionPage);
		} else {
			super.doPrevious();
		}
	}

	@Override public final void doNext() {
		if (outOfOrderPage != null) {
			outOfOrderPage = null;
			returnAfterOutOfOrderPage(state.imageUploadPage, state.conversionPage);
		} else {
			super.doNext();
		}
	}

	@Override protected boolean onCancelRequest() {
		if (state == null || state.uuid == null)
			return true; // Allow closing - nothing in progress
		boolean confirmed = Gui.showMessageBox(this,
				I18n.WIZARD.getString("ImageCreation.Message.yesNo.cancelRequest"),
				MessageType.QUESTION_YESNO, null, null);
		if (confirmed) {
			QuickTimer.scheduleOnce(new Task() {
				@Override
				public void fire() {
					if (state != null && state.upload != null) {
						state.upload.cancelError("Cancelled through aborting wizard");
						// As we're creating a new VM, delete base image aswell
						try {
							ThriftManager.getSatClient()
									.deleteImageBase(Session.getSatelliteToken(), state.uuid);
						} catch (TException e) {
							LOGGER.debug("Error canceling upload on sat: ", e);
						}
					}
				}
			});
		}
		return confirmed;
	}

	@Override public boolean wantConfirmQuit() {
		return state != null && state.uuid != null;
	}

	@Override public void escapePressed() {
		doCancel();
	}

	@Override public void onApplicationQuit() {
		if (state != null && state.upload != null) {
			state.upload.cancelError("Application quit (via ImageCreationWizard)");
		}
	}

	@Override
	protected void doCleanup() {
		if (state != null) {
			state.upload = null;
			state = null;
		}
		containerDefinition = null;
		currentPages.clear();
	}
}