Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: d8ad7f10576dae3a968d293fbd31d9bcb9d363ea (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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*******************************************************************************
 * Copyright (c) 2009, 2013 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
 *     Ericsson AB - Ongoing development
 *******************************************************************************/
package org.eclipse.equinox.internal.p2.tests.verifier;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.internal.adaptor.EclipseAdaptorMsg;
import org.eclipse.core.runtime.internal.adaptor.MessageHelper;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.engine.IProfile;
import org.eclipse.equinox.p2.engine.IProfileRegistry;
import org.eclipse.equinox.p2.query.IQueryResult;
import org.eclipse.equinox.p2.query.QueryUtil;
import org.eclipse.osgi.framework.internal.core.Constants;
import org.eclipse.osgi.service.resolver.*;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.Bundle;
import org.osgi.service.packageadmin.PackageAdmin;

/**
 * Application which verifies an install.
 * 
 * @since 1.0
 */
public class VerifierApplication implements IApplication {

	private static final File DEFAULT_PROPERTIES_FILE = new File("verifier.properties"); //$NON-NLS-1$
	private static final String ARG_PROPERTIES = "-verifier.properties"; //$NON-NLS-1$
	private IProvisioningAgent agent;
	private Properties properties = null;
	private List ignoreResolved = null;

	/*
	 * Create and return an error status with the given message.
	 */
	private static IStatus createError(String message) {
		return new Status(IStatus.ERROR, Activator.PLUGIN_ID, message);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
	 */
	public Object start(IApplicationContext context) throws Exception {
		String[] args = (String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS);
		processArguments(args);

		agent = (IProvisioningAgent) ServiceHelper.getService(Activator.getBundleContext(), IProvisioningAgent.SERVICE_NAME);

		IStatus result = verify();
		if (!result.isOK()) {
			//			PrintWriter out = new PrintWriter(new FileWriter(new File("c:/tmp/dropins-debug.txt")));
			PrintWriter out = new PrintWriter(new OutputStreamWriter(System.err));
			out.println("Error from dropin verifier application: " + result.getMessage()); //$NON-NLS-1$
			Throwable t = result.getException();
			if (t != null)
				t.printStackTrace(out);
			out.close();
			LogHelper.log(result);
		}
		return result.isOK() ? IApplication.EXIT_OK : new Integer(13);
	}

	/*
	 * Go through the command-line args and pull out interesting ones
	 * for later consumption.
	 */
	private void processArguments(String[] args) {
		if (args == null)
			return;

		for (int i = 1; i < args.length; i++) {
			if (ARG_PROPERTIES.equals(args[i - 1])) {
				String filename = args[i];
				if (filename.startsWith("-")) //$NON-NLS-1$
					continue;
				try {
					properties = readProperties(new File(filename));
				} catch (IOException e) {
					// TODO
					e.printStackTrace();
					// fall through to load default
				}
				continue;
			}
		}

		// problems loading properties file or none specified so look for a default
		if (properties == null) {
			try {
				if (DEFAULT_PROPERTIES_FILE.exists())
					properties = readProperties(DEFAULT_PROPERTIES_FILE);
			} catch (IOException e) {
				// TODO 
				e.printStackTrace();
			}
		}
		if (properties == null)
			properties = new Properties();
	}

	/*
	 * Read and return a properties file at the given location.
	 */
	private Properties readProperties(File file) throws IOException {
		Properties result = new Properties();
		InputStream input = null;
		try {
			input = new BufferedInputStream(new FileInputStream(file));
			result.load(input);
			return result;
		} finally {
			if (input != null)
				try {
					input.close();
				} catch (IOException e) {
					// ignore
				}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		// nothing to do
	}

	/*
	 * Return a boolean value indicating whether or not the bundle with the given symbolic name
	 * should be considered when looking at bundles which are not resolved in the system.
	 * TODO the call to this method was removed. we should add it back
	 */
	protected boolean shouldCheckResolved(String bundle) {
		if (ignoreResolved == null) {
			ignoreResolved = new ArrayList();
			String list = properties.getProperty("ignore.unresolved");
			if (list == null)
				return true;
			for (StringTokenizer tokenizer = new StringTokenizer(list, ","); tokenizer.hasMoreTokens();)
				ignoreResolved.add(tokenizer.nextToken().trim());
		}
		for (Iterator iter = ignoreResolved.iterator(); iter.hasNext();) {
			if (bundle.equals(iter.next()))
				return false;
		}
		return true;
	}

	private List getAllBundles() {
		PlatformAdmin platformAdmin = (PlatformAdmin) ServiceHelper.getService(Activator.getBundleContext(), PlatformAdmin.class.getName());
		PackageAdmin packageAdmin = (PackageAdmin) ServiceHelper.getService(Activator.getBundleContext(), PackageAdmin.class.getName());
		State state = platformAdmin.getState(false);
		List result = new ArrayList();

		BundleDescription[] bundles = state.getBundles();
		for (int i = 0; i < bundles.length; i++) {
			BundleDescription bundle = bundles[i];
			Bundle[] versions = packageAdmin.getBundles(bundle.getSymbolicName(), bundle.getVersion().toString());
			for (int j = 0; j < versions.length; j++)
				result.add(versions[j]);
		}
		return result;
	}

	/*
	 * Check to ensure all of the bundles in the system are resolved.
	 * 
	 * Copied and modified from EclipseStarter#logUnresolvedBundles.
	 * This method prints out all the reasons while asking the resolver directly
	 * will only print out the first reason.
	 */
	private IStatus checkResolved() {
		List allProblems = new ArrayList();
		PlatformAdmin platformAdmin = (PlatformAdmin) ServiceHelper.getService(Activator.getBundleContext(), PlatformAdmin.class.getName());
		State state = platformAdmin.getState(false);
		StateHelper stateHelper = platformAdmin.getStateHelper();

		// first lets look for missing leaf constraints (bug 114120)
		VersionConstraint[] leafConstraints = stateHelper.getUnsatisfiedLeaves(state.getBundles());
		// hash the missing leaf constraints by the declaring bundles
		Map missing = new HashMap();
		for (int i = 0; i < leafConstraints.length; i++) {
			// only include non-optional and non-dynamic constraint leafs
			if (leafConstraints[i] instanceof BundleSpecification && ((BundleSpecification) leafConstraints[i]).isOptional())
				continue;
			if (leafConstraints[i] instanceof ImportPackageSpecification) {
				if (ImportPackageSpecification.RESOLUTION_OPTIONAL.equals(((ImportPackageSpecification) leafConstraints[i]).getDirective(Constants.RESOLUTION_DIRECTIVE)))
					continue;
				if (ImportPackageSpecification.RESOLUTION_DYNAMIC.equals(((ImportPackageSpecification) leafConstraints[i]).getDirective(Constants.RESOLUTION_DIRECTIVE)))
					continue;
			}
			BundleDescription bundleDesc = leafConstraints[i].getBundle();
			ArrayList constraints = (ArrayList) missing.get(bundleDesc);
			if (constraints == null) {
				constraints = new ArrayList();
				missing.put(bundleDesc, constraints);
			}
			constraints.add(leafConstraints[i]);
		}

		// found some bundles with missing leaf constraints; log them first 
		if (missing.size() > 0) {
			for (Iterator iter = missing.keySet().iterator(); iter.hasNext();) {
				BundleDescription description = (BundleDescription) iter.next();
				String generalMessage = NLS.bind(EclipseAdaptorMsg.ECLIPSE_STARTUP_ERROR_BUNDLE_NOT_RESOLVED, description.getLocation());
				ArrayList constraints = (ArrayList) missing.get(description);
				for (Iterator inner = constraints.iterator(); inner.hasNext();) {
					String message = generalMessage + " Reason: " + MessageHelper.getResolutionFailureMessage((VersionConstraint) inner.next()); //$NON-NLS-1$
					allProblems.add(createError(message));
				}
			}
		}

		// There may be some bundles unresolved for other reasons, causing the system to be unresolved
		// log all unresolved constraints now
		List allBundles = getAllBundles();
		for (Iterator i = allBundles.iterator(); i.hasNext();) {
			Bundle bundle = (Bundle) i.next();
			if (bundle.getState() == Bundle.INSTALLED) {
				String generalMessage = NLS.bind(EclipseAdaptorMsg.ECLIPSE_STARTUP_ERROR_BUNDLE_NOT_RESOLVED, bundle);
				BundleDescription description = state.getBundle(bundle.getBundleId());
				// for some reason, the state does not know about that bundle
				if (description == null)
					continue;
				VersionConstraint[] unsatisfied = stateHelper.getUnsatisfiedConstraints(description);
				if (unsatisfied.length > 0) {
					// the bundle wasn't resolved due to some of its constraints were unsatisfiable
					for (int j = 0; j < unsatisfied.length; j++)
						allProblems.add(createError(generalMessage + " Reason: " + MessageHelper.getResolutionFailureMessage(unsatisfied[j]))); //$NON-NLS-1$
				} else {
					ResolverError[] resolverErrors = state.getResolverErrors(description);
					for (int j = 0; j < resolverErrors.length; j++) {
						if (shouldAdd(resolverErrors[j])) {
							allProblems.add(createError(generalMessage + " Reason: " + resolverErrors[j].toString())); //$NON-NLS-1$
						}
					}
				}
			}
		}
		MultiStatus result = new MultiStatus(Activator.PLUGIN_ID, IStatus.OK, "Problems checking resolved bundles.", null); //$NON-NLS-1$
		for (Iterator iter = allProblems.iterator(); iter.hasNext();)
			result.add((IStatus) iter.next());
		return result;
	}

	/*
	 * Return a boolean value indicating whether or not the given resolver error should be 
	 * added to our results.
	 */
	private boolean shouldAdd(ResolverError error) {
		// ignore EE problems? default value is true
		String prop = properties.getProperty("ignore.ee"); //$NON-NLS-1$
		boolean ignoreEE = prop == null || Boolean.valueOf(prop).booleanValue();
		if (ResolverError.MISSING_EXECUTION_ENVIRONMENT == error.getType() && ignoreEE)
			return false;
		return true;
	}

	/*
	 * Ensure we have a profile registry and can access the SELF profile.
	 */
	private IStatus checkProfileRegistry() {
		IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
		if (registry == null)
			return createError("Profile registry service not available."); //$NON-NLS-1$
		IProfile profile = registry.getProfile(IProfileRegistry.SELF);
		if (profile == null)
			return createError("SELF profile not available in profile registry."); //$NON-NLS-1$
		if (!Boolean.FALSE.toString().equals(properties.get("checkPresenceOfVerifier"))) {
			IQueryResult results = profile.query(QueryUtil.createIUQuery(Activator.PLUGIN_ID), null);
			if (results.isEmpty())
				return createError(NLS.bind("IU for {0} not found in SELF profile.", Activator.PLUGIN_ID)); //$NON-NLS-1$
		}
		return Status.OK_STATUS;
	}

	/*
	 * Perform all of the verification checks.
	 */
	public IStatus verify() {
		String message = "Problems occurred during verification."; //$NON-NLS-1$
		MultiStatus result = new MultiStatus(Activator.PLUGIN_ID, IStatus.OK, message, null);

		// ensure all the bundles are resolved
		IStatus temp = checkResolved();
		if (!temp.isOK())
			result.merge(temp);

		// ensure we have a profile registry
		temp = checkProfileRegistry();
		if (!temp.isOK())
			result.merge(temp);

		temp = hasProfileFlag();
		if (!temp.isOK())
			result.merge(temp);

		temp = checkAbsenceOfBundles();
		if (!temp.isOK())
			result.merge(temp);

		temp = checkPresenceOfBundles();
		if (!temp.isOK())
			result.merge(temp);

		temp = checkSystemProperties();
		if (!temp.isOK())
			result.merge(temp);

		return result;
	}

	private IStatus checkSystemProperties() {
		final String ABSENT_SYS_PROPERTY = "not.sysprop.";
		final String PRESENT_SYS_PROPERTY = "sysprop.";
		MultiStatus result = new MultiStatus(Activator.PLUGIN_ID, IStatus.ERROR, "System properties validation", null);

		Set<Entry<Object, Object>> entries = properties.entrySet();
		for (Entry<Object, Object> entry : entries) {
			String key = (String) entry.getKey();
			if (key.startsWith(ABSENT_SYS_PROPERTY)) {
				String property = key.substring(ABSENT_SYS_PROPERTY.length());
				if (System.getProperty(property) != null)
					result.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Property " + property + " should not be set."));
			}
			if (key.startsWith(PRESENT_SYS_PROPERTY)) {
				String property = key.substring(PRESENT_SYS_PROPERTY.length());
				String foundValue = System.getProperty(property);
				if (!entry.getValue().equals(foundValue))
					result.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Property " + property + " should be set to " + entry.getValue() + " and is set to " + foundValue + "."));
			}
		}
		if (result.getChildren().length == 0)
			return Status.OK_STATUS;
		return result;
	}

	private IStatus checkAbsenceOfBundles() {
		MultiStatus result = new MultiStatus(Activator.PLUGIN_ID, IStatus.ERROR, "Some bundles should not be there", null);
		String unexpectedBundlesString = properties.getProperty("unexpectedBundleList");
		if (unexpectedBundlesString == null)
			return Status.OK_STATUS;
		String[] unexpectedBundles = unexpectedBundlesString.split(",");
		for (String bsn : unexpectedBundles) {
			if (containsBundle(bsn)) {
				result.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, bsn + " should not have been found in the install"));
			}
		}
		if (result.getChildren().length == 0)
			return Status.OK_STATUS;
		return result;
	}

	private IStatus checkPresenceOfBundles() {
		MultiStatus result = new MultiStatus(Activator.PLUGIN_ID, IStatus.ERROR, "Some bundles should not be there", null);
		String expectedBundlesString = properties.getProperty("expectedBundleList");
		if (expectedBundlesString == null)
			return Status.OK_STATUS;
		String[] expectedBundles = expectedBundlesString.split(",");
		for (String bsn : expectedBundles) {
			if (!containsBundle(bsn)) {
				result.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, bsn + " is missing from the install"));
			}
		}
		if (result.getChildren().length == 0)
			return Status.OK_STATUS;
		return result;
	}

	private boolean containsBundle(String bsn) {
		PlatformAdmin platformAdmin = (PlatformAdmin) ServiceHelper.getService(Activator.getBundleContext(), PlatformAdmin.class.getName());
		State state = platformAdmin.getState(false);
		return state.getBundle(bsn, null) != null;
	}

	private IStatus hasProfileFlag() {
		if (properties.getProperty("checkProfileResetFlag") == null || "false".equals(properties.getProperty("checkProfileResetFlag")))
			return Status.OK_STATUS;
		//Make sure that the profile is already loaded
		IProfileRegistry reg = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
		IProfile profile = reg.getProfile(IProfileRegistry.SELF);
		String profileId = profile.getProfileId();

		long history[] = reg.listProfileTimestamps(profileId);
		long lastTimestamp = history[history.length - 1];
		if (IProfile.STATE_SHARED_INSTALL_VALUE_NEW.equals(reg.getProfileStateProperties(profileId, lastTimestamp).get(IProfile.STATE_PROP_SHARED_INSTALL))) {
			return Status.OK_STATUS;
		}
		if (history.length == 1) {
			return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The flag indicating that a profile has been reset is incorrectly setup");
		}

		long previousToLastTimestamp = history[history.length - 2];
		if (IProfile.STATE_SHARED_INSTALL_VALUE_NEW.equals(reg.getProfileStateProperties(profileId, previousToLastTimestamp).get(IProfile.STATE_PROP_SHARED_INSTALL))) {
			return Status.OK_STATUS;
		}

		return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The flag indicating that a profile has been reset is incorrectly setup");
	}
}

Back to the top