Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 4ceb765a1e66ca56b278622519c94c5db4b89aa0 (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
/*******************************************************************************
 * Copyright (c) 2007 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.equinox.internal.p2.installer;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.equinox.p2.artifact.repository.IArtifactRepositoryManager;
import org.eclipse.equinox.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.p2.director.IDirector;
import org.eclipse.equinox.p2.engine.IProfileRegistry;
import org.eclipse.equinox.p2.engine.Profile;
import org.eclipse.equinox.p2.installer.IInstallDescription;
import org.eclipse.equinox.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.p2.metadata.repository.IMetadataRepository;
import org.eclipse.equinox.p2.metadata.repository.IMetadataRepositoryManager;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.osgi.service.environment.EnvironmentInfo;
import org.eclipse.osgi.service.resolver.VersionRange;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;

/**
 * This operation performs installation or update of an Eclipse-based product.
 */
public class InstallUpdateProductOperation implements IRunnableWithProgress {

	/**
	 * This constant comes from value of FrameworkAdmin.SERVICE_PROP_KEY_LAUNCHER_NAME.
	 * This profile property is being used as a short term solution for branding of the launcher.
	 */
	private static final String PROP_LAUNCHER_NAME = "org.eclipse.equinox.frameworkhandler.launcher.name";

	/**
	 * Constant for config folder property copied from EclipseTouchpoint.CONFIG_FOLDER.
	 */
	private final static String CONFIG_FOLDER = "eclipse.configurationFolder";

	private IArtifactRepositoryManager artifactRepoMan;
	private BundleContext bundleContext;
	private IDirector director;
	private final IInstallDescription installDescription;
	private boolean isInstall = true;
	private IMetadataRepositoryManager metadataRepoMan;
	private IProfileRegistry profileRegistry;
	private IStatus result;

	private ArrayList serviceReferences = new ArrayList();

	public InstallUpdateProductOperation(BundleContext context, IInstallDescription description) {
		this.bundleContext = context;
		this.installDescription = description;
	}

	/**
	 * Determine what top level installable units should be installed by the director
	 */
	private IInstallableUnit[] computeUnitsToInstall() throws CoreException {
		IInstallableUnit root = installDescription.getRootInstallableUnit();
		//The install description just contains a prototype of the root IU. We need
		//to find the real IU in an available metadata repository
		return new IInstallableUnit[] {findUnit(root.getId(), root.getVersion())};
	}

	/**
	 * Create and return the profile into which units will be installed.
	 */
	private Profile createProfile() {
		Profile profile = getProfile();
		if (profile == null) {
			profile = new Profile(installDescription.getProductName());
			profile.setValue(Profile.PROP_INSTALL_FOLDER, installDescription.getInstallLocation().toString());
			profile.setValue(Profile.PROP_FLAVOR, installDescription.getFlavor());
			profile.setValue(PROP_LAUNCHER_NAME, installDescription.getLauncherName());
			EnvironmentInfo info = (EnvironmentInfo) ServiceHelper.getService(InstallerActivator.getDefault().getContext(), EnvironmentInfo.class.getName());
			String env = "osgi.os=" + info.getOS() + ",osgi.ws=" + info.getWS() + ",osgi.arch=" + info.getOSArch();
			profile.setValue(Profile.PROP_ENVIRONMENTS, env);
			profileRegistry.addProfile(profile);
		}
		return profile;
	}

	/**
	 * Throws an exception of severity error with the given error message.
	 */
	private CoreException fail(String message) {
		return fail(message, null);
	}

	/**
	 * Throws an exception of severity error with the given error message.
	 */
	private CoreException fail(String message, Throwable throwable) {
		return new CoreException(new Status(IStatus.ERROR, InstallerActivator.PI_INSTALLER, message, throwable));
	}

	/**
	 * Finds and returns the installable unit with the given id, and optionally the
	 * given version.
	 */
	private IInstallableUnit findUnit(String id, Version version) throws CoreException {
		if (id == null)
			throw fail("Installable unit id not specified");
		VersionRange range = VersionRange.emptyRange;
		if (version != null)
			range = new VersionRange(version, true, version, true);
		IMetadataRepository[] repos = metadataRepoMan.getKnownRepositories();
		for (int i = 0; i < repos.length; i++) {
			IInstallableUnit[] found = repos[i].query(id, range, null, true, null);
			if (found.length > 0)
				return found[0];
		}
		throw fail("Installable unit not found: " + id);
	}

	/**
	 * Returns the profile being installed into.
	 */
	private Profile getProfile() {
		return profileRegistry.getProfile(installDescription.getProductName());
	}

	/**
	 * Returns the result of the install operation, or <code>null</code> if
	 * no install operation has been run.
	 */
	public IStatus getResult() {
		return result;
	}

	private Object getService(String name) throws CoreException {
		ServiceReference ref = bundleContext.getServiceReference(name);
		if (ref == null)
			throw fail("Install requires a service that is not available: " + name);
		Object service = bundleContext.getService(ref);
		if (service == null)
			throw fail("Install requires a service implementation that is not available: " + name);
		serviceReferences.add(ref);
		return service;
	}

	/**
	 * Performs the actual product install or update.
	 */
	private void install(SubMonitor monitor) throws CoreException {
		prepareMetadataRepository();
		prepareArtifactRepository();
		Profile p = createProfile();
		IInstallableUnit[] toInstall = computeUnitsToInstall();
		monitor.worked(5);

		IStatus s;
		if (isInstall) {
			monitor.subTask("Installing...");
			s = director.install(toInstall, p, null, monitor.newChild(90));
		} else {
			monitor.subTask("Updating...");
			IInstallableUnit[] toUninstall = computeUnitsToUninstall(p);
			s = director.replace(toUninstall, toInstall, p, monitor.newChild(90));
		}
		if (!s.isOK())
			throw new CoreException(s);
	}

	/**
	 * This profile is being updated; return the units to uninstall from the profile.
	 */
	private IInstallableUnit[] computeUnitsToUninstall(Profile profile) {
		ArrayList units = new ArrayList();
		for (Iterator it = profile.getInstallableUnits(); it.hasNext();)
			units.add(it.next());
		return (IInstallableUnit[]) units.toArray(new IInstallableUnit[units.size()]);
	}

	/**
	 * Returns whether this operation represents the product being installed
	 * for the first time, in a new profile.
	 */
	public boolean isFirstInstall() {
		return isInstall;
	}

	private void postInstall() {
		for (Iterator it = serviceReferences.iterator(); it.hasNext();) {
			ServiceReference sr = (ServiceReference) it.next();
			bundleContext.ungetService(sr);
		}
		serviceReferences.clear();
	}

	private void preInstall() throws CoreException {
		//obtain required services
		serviceReferences.clear();
		director = (IDirector) getService(IDirector.class.getName());
		metadataRepoMan = (IMetadataRepositoryManager) getService(IMetadataRepositoryManager.class.getName());
		artifactRepoMan = (IArtifactRepositoryManager) getService(IArtifactRepositoryManager.class.getName());
		profileRegistry = (IProfileRegistry) getService(IProfileRegistry.class.getName());
	}

	private void prepareArtifactRepository() {
		URL artifactRepo = installDescription.getArtifactRepository();
		if (artifactRepo != null)
			artifactRepoMan.loadRepository(artifactRepo, null);
	}

	private void prepareMetadataRepository() {
		URL metadataRepo = installDescription.getMetadataRepository();
		if (metadataRepo != null)
			metadataRepoMan.loadRepository(metadataRepo, null);
	}

	/**
	 * Registers information about the agent with the installed product,
	 * so it knows how to kick the agent to perform updates.
	 */
	private void registerAgent() throws CoreException {
		Profile profile = getProfile();
		File config = null;
		String configString = profile.getValue(CONFIG_FOLDER);
		if (configString == null)
			config = new File(new File(profile.getValue(Profile.PROP_INSTALL_FOLDER)), "configuration");
		else
			config = new File(configString);
		File agentFolder = new File(config, "org.eclipse.equinox.p2.installer");
		agentFolder.mkdirs();
		File agentFile = new File(agentFolder, "agent.properties");

		String commands = computeAgentCommandLine();

		Properties agentData = new Properties();
		agentData.put("eclipse.commands", commands);
		OutputStream out = null;
		try {
			out = new BufferedOutputStream(new FileOutputStream(agentFile));
			agentData.store(out, commands);
		} catch (IOException e) {
			throw fail("Error writing agent configuration data", e);
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				//ignore
			}
		}
	}

	/**
	 * Returns the command line string that will launch the agent.
	 */
	private String computeAgentCommandLine() throws CoreException {
		String commands = System.getProperty("eclipse.commands");
		StringBuffer output = new StringBuffer(commands.length());
		StringTokenizer tokens = new StringTokenizer(commands, "\n");
		String launcherName = null;
		while (tokens.hasMoreTokens()) {
			String next = tokens.nextToken();
			//discard the launcher token
			if ("-launcher".equals(next) && tokens.hasMoreTokens()) {
				launcherName = tokens.nextToken();
			} else {
				output.append(' ');
				output.append(next);
			}
		}
		if (launcherName == null)
			throw fail("Unable to determine agent launcher name");
		return launcherName + output.toString();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
	 */
	public void run(IProgressMonitor pm) throws InvocationTargetException {
		SubMonitor monitor = SubMonitor.convert(pm, "Preparing to install", 100);
		try {
			try {
				preInstall();
				isInstall = getProfile() == null;
				String taskName = isInstall ? "Installing {0}" : "Updating {0}";
				monitor.setTaskName(NLS.bind(taskName, installDescription.getProductName()));
				install(monitor);
				result = new Status(IStatus.OK, InstallerActivator.PI_INSTALLER, isInstall ? "Install complete" : "Update complete", null);
				monitor.setTaskName("Some final housekeeping");
				if (isInstall)
					registerAgent();
			} finally {
				postInstall();
			}
		} catch (CoreException e) {
			this.result = e.getStatus();
			throw new InvocationTargetException(e);
		} finally {
			monitor.done();
		}
	}
}

Back to the top