Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 94ff050686f5860b2bb6695a02eed3c1229dbddf (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
/*******************************************************************************
 * Copyright (c) 2013 Red Hat, Inc. 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:
 *     Red Hat, Inc. - initial API and implementation
 *******************************************************************************/
package org.eclipse.equinox.internal.p2.operations;

import java.util.*;
import java.util.Map.Entry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.equinox.internal.p2.director.ProfileChangeRequest;
import org.eclipse.equinox.p2.engine.*;
import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery;
import org.eclipse.equinox.p2.metadata.*;
import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil;
import org.eclipse.equinox.p2.metadata.expression.IMatchExpression;
import org.eclipse.equinox.p2.planner.IPlanner;
import org.eclipse.equinox.p2.planner.IProfileChangeRequest;
import org.eclipse.equinox.p2.query.*;

public class RequestFlexer {
	final String INCLUSION_RULES = "org.eclipse.equinox.p2.internal.inclusion.rules"; //$NON-NLS-1$
	final String INCLUSION_OPTIONAL = "OPTIONAL"; //$NON-NLS-1$
	final String INCLUSION_STRICT = "STRICT"; //$NON-NLS-1$

	IPlanner planner;

	private boolean allowInstalledUpdate = false;
	private boolean allowInstalledRemoval = false;
	private boolean allowDifferentVersion = false;
	private boolean allowPartialInstall = false;
	private ProvisioningContext provisioningContext;

	Set<IRequirement> requirementsForElementsBeingInstalled = new HashSet<IRequirement>();
	Set<IRequirement> requirementsForElementsAlreadyInstalled = new HashSet<IRequirement>();
	Map<IRequirement, Map> propertiesPerRequirement = new HashMap();
	Map<IRequirement, List<String>> removedPropertiesPerRequirement = new HashMap();

	IProfile profile;

	private boolean foundDifferentVersionsForElementsToInstall = false;
	private boolean foundDifferentVersionsForElementsInstalled = false;
	private Set<IInstallableUnit> futureOptionalIUs;

	public RequestFlexer(IPlanner planner) {
		this.planner = planner;
	}

	public void setAllowInstalledElementChange(boolean allow) {
		allowInstalledUpdate = allow;
	}

	public void setAllowInstalledElementRemoval(boolean allow) {
		allowInstalledRemoval = allow;
	}

	public void setAllowDifferentVersion(boolean allow) {
		allowDifferentVersion = allow;
	}

	public void setAllowPartialInstall(boolean allow) {
		allowPartialInstall = allow;
	}

	public void setProvisioningContext(ProvisioningContext context) {
		provisioningContext = context;
	}

	public IProfileChangeRequest getChangeRequest(IProfileChangeRequest request, IProfile prof, IProgressMonitor monitor) {
		this.profile = prof;
		IProfileChangeRequest loosenedRequest = computeLooseRequest(request);
		if (canShortCircuit(request)) {
			return null;
		}
		IProvisioningPlan intermediaryPlan = resolve(loosenedRequest);
		if (!intermediaryPlan.getStatus().isOK())
			return null;
		if (intermediaryPlan.getAdditions().query(QueryUtil.ALL_UNITS, new NullProgressMonitor()).isEmpty() && intermediaryPlan.getRemovals().query(QueryUtil.ALL_UNITS, new NullProgressMonitor()).isEmpty())
			//No changes, we can't return anything
			return null;
		IProfileChangeRequest effectiveRequest = computeEffectiveChangeRequest(intermediaryPlan, loosenedRequest, request);
		if (effectiveRequest.getAdditions().isEmpty() && effectiveRequest.getRemovals().isEmpty())
			return null;
		return effectiveRequest;
	}

	private boolean canShortCircuit(IProfileChangeRequest originalRequest) {
		//Case where the user is asking to install only some of the requested IUs but there is only one IU to install. 
		if (allowPartialInstall)
			if (originalRequest.getAdditions().size() == 1 && originalRequest.getRemovals().isEmpty())
				return true;

		//When we can find a different version of the IU but the only version available is the one the user is asking to install
		if (allowDifferentVersion && !allowPartialInstall && !allowInstalledRemoval && !allowInstalledUpdate)
			if (!foundDifferentVersionsForElementsToInstall)
				return true;

		if (allowInstalledUpdate && !allowDifferentVersion && !allowPartialInstall && !allowInstalledRemoval)
			if (!foundDifferentVersionsForElementsInstalled)
				return true;

		return false;
	}

	//From the loosened request and the plan resulting from its resolution, create a new profile change request representing the delta between where the profile currently is 
	// and the plan returned.
	//To perform this efficiently, this relies on a traversal of the requirements that are part of the loosened request.  
	private IProfileChangeRequest computeEffectiveChangeRequest(IProvisioningPlan intermediaryPlan, IProfileChangeRequest loosenedRequest, IProfileChangeRequest originalRequest) {
		IProfileChangeRequest finalChangeRequest = planner.createChangeRequest(profile);

		for (IRequirement beingInstalled : requirementsForElementsBeingInstalled) {
			IQuery<IInstallableUnit> query = QueryUtil.createMatchQuery(beingInstalled.getMatches());
			IQueryResult<IInstallableUnit> matches = intermediaryPlan.getFutureState().query(QueryUtil.createLatestQuery(query), null);
			IInstallableUnit replacementIU = null;
			if (!matches.isEmpty()) {
				replacementIU = matches.iterator().next();
				finalChangeRequest.add(replacementIU);
				adaptIUPropertiesToNewIU(beingInstalled, replacementIU, finalChangeRequest);
			}
		}

		for (IRequirement alreadyInstalled : requirementsForElementsAlreadyInstalled) {
			IQuery<IInstallableUnit> query = QueryUtil.createMatchQuery(alreadyInstalled.getMatches());
			IQueryResult<IInstallableUnit> matches = intermediaryPlan.getFutureState().query(QueryUtil.createLatestQuery(query), null);
			IInstallableUnit potentialRootChange = null;
			if (!matches.isEmpty())
				potentialRootChange = matches.iterator().next();

			IQueryResult<IInstallableUnit> iuAlreadyInstalled = profile.available(query, new NullProgressMonitor());

			if (!iuAlreadyInstalled.isEmpty()) {//This deals with the case where the root has not changed
				if (potentialRootChange != null && iuAlreadyInstalled.toUnmodifiableSet().contains(potentialRootChange))
					continue;
			}
			finalChangeRequest.removeAll(iuAlreadyInstalled.toUnmodifiableSet());
			if (potentialRootChange != null) {
				if (!finalChangeRequest.getAdditions().contains(potentialRootChange)) {//So we don't add the same IU twice for addition
					finalChangeRequest.add(potentialRootChange);
					adaptIUPropertiesToNewIU(alreadyInstalled, potentialRootChange, finalChangeRequest);
				}
			}
		}

		finalChangeRequest.removeAll(originalRequest.getRemovals());
		if (originalRequest.getExtraRequirements() != null)
			finalChangeRequest.addExtraRequirements(originalRequest.getExtraRequirements());
		return finalChangeRequest;
	}

	private void adaptIUPropertiesToNewIU(IRequirement beingInstalled, IInstallableUnit newIU, IProfileChangeRequest finalChangeRequest) {
		Map<String, String> associatedProperties = propertiesPerRequirement.get(beingInstalled);
		if (associatedProperties != null) {
			Set<Entry<String, String>> entries = associatedProperties.entrySet();
			for (Entry<String, String> entry : entries) {
				finalChangeRequest.setInstallableUnitProfileProperty(newIU, entry.getKey(), entry.getValue());
			}
		}
		List<String> removedProperties = removedPropertiesPerRequirement.get(beingInstalled);
		if (removedProperties != null) {
			for (String toRemove : removedProperties) {
				finalChangeRequest.removeInstallableUnitProfileProperty(newIU, toRemove);
			}
		}
	}

	//Create a request where the original requirements are "loosened" according to flags specified in this instance
	//The resulting profile change request uses the requirements specified using p2QL and those appear in the extraRequirements.
	private IProfileChangeRequest computeLooseRequest(IProfileChangeRequest originalRequest) {
		IProfileChangeRequest loosenedRequest = planner.createChangeRequest(profile);
		loosenUpOriginalRequest(loosenedRequest, originalRequest);
		loosenUpInstalledSoftware(loosenedRequest, originalRequest);
		return loosenedRequest;
	}

	private boolean removalRequested(IInstallableUnit removalRequested, IProfileChangeRequest request) {
		return request.getRemovals().contains(removalRequested);
	}

	private IProvisioningPlan resolve(IProfileChangeRequest temporaryRequest) {
		temporaryRequest.setProfileProperty("_internal_user_defined_", "true");
		return planner.getProvisioningPlan(temporaryRequest, provisioningContext, null);
	}

	//Loosen the request originally emitted.
	//For example if the user said "install A 1.0", then a new Requirement is added saying (install A 1.0 or install A 2.0), this depending on the configuration flags 
	private void loosenUpOriginalRequest(IProfileChangeRequest newRequest, IProfileChangeRequest originalRequest) {
		//First deal with the IUs that are being added
		Collection<IInstallableUnit> requestedAdditions = originalRequest.getAdditions();
		for (IInstallableUnit addedIU : requestedAdditions) {
			Collection<IInstallableUnit> potentialUpdates = allowDifferentVersion ? findAllVersionsAvailable(addedIU) : new ArrayList();
			foundDifferentVersionsForElementsToInstall = (foundDifferentVersionsForElementsToInstall || (potentialUpdates.size() == 0 ? false : true));
			potentialUpdates.add(addedIU); //Make sure that we include the IU that we were initially trying to install

			Collection<IRequirement> newRequirement = new ArrayList<IRequirement>(1);
			IRequirement req = createORRequirement(potentialUpdates, allowPartialInstall || isRequestedInstallationOptional(addedIU, originalRequest));
			newRequirement.add(req);
			newRequest.addExtraRequirements(newRequirement);
			requirementsForElementsBeingInstalled.addAll(newRequirement);
			rememberIUProfileProperties(addedIU, req, originalRequest, false);
		}

		//Deal with the IUs requested for removal
		newRequest.removeAll(originalRequest.getRemovals());

		//Deal with extra requirements that could have been specified
		if (originalRequest.getExtraRequirements() != null)
			newRequest.addExtraRequirements(originalRequest.getExtraRequirements());
	}

	//This keeps track for each requirement created (those created to loosen the constraint), of the original IU and the properties associated with it in the profile
	//This is used for more easily construct the final profile change request
	private void rememberIUProfileProperties(IInstallableUnit iu, IRequirement req, IProfileChangeRequest originalRequest, boolean includeProfile) {
		Map<String, String> allProperties = new HashMap<String, String>();
		if (includeProfile) {
			Map<String, String> tmp = new HashMap(profile.getInstallableUnitProperties(iu));
			List<String> propertiesToRemove = ((ProfileChangeRequest) originalRequest).getInstallableUnitProfilePropertiesToRemove().get(iu);
			if (propertiesToRemove != null) {
				for (String toRemove : propertiesToRemove) {
					tmp.remove(toRemove);
				}
			}
			allProperties.putAll(tmp);
		}

		Map<String, String> propertiesInRequest = ((ProfileChangeRequest) originalRequest).getInstallableUnitProfilePropertiesToAdd().get(iu);
		if (propertiesInRequest != null)
			allProperties.putAll(propertiesInRequest);

		propertiesPerRequirement.put(req, allProperties);

		List<String> removalInRequest = ((ProfileChangeRequest) originalRequest).getInstallableUnitProfilePropertiesToRemove().get(iu);
		if (removalInRequest != null)
			removedPropertiesPerRequirement.put(req, removalInRequest);
	}

	private boolean isRequestedInstallationOptional(IInstallableUnit iu, IProfileChangeRequest originalRequest) {
		Map<String, String> match = ((ProfileChangeRequest) originalRequest).getInstallableUnitProfilePropertiesToAdd().get(iu);
		if (match == null)
			return false;
		return INCLUSION_OPTIONAL.equals(match.get(INCLUSION_RULES));
	}

	private Collection<IInstallableUnit> findAllVersionsAvailable(IInstallableUnit iu) {
		Collection<IInstallableUnit> allVersions = new HashSet();
		allVersions.addAll(findIUsWithSameId(iu));
		allVersions.addAll(findUpdates(iu));
		return allVersions;
	}

	private Collection<IInstallableUnit> findIUsWithSameId(IInstallableUnit iu) {
		return provisioningContext.getMetadata(null).query(QueryUtil.createIUQuery(iu.getId()), null).toUnmodifiableSet();
	}

	private Collection<IInstallableUnit> findUpdates(IInstallableUnit iu) {
		Collection<IInstallableUnit> availableUpdates = new HashSet<IInstallableUnit>();
		IQueryResult<IInstallableUnit> updatesAvailable = planner.updatesFor(iu, provisioningContext, null);
		for (Iterator<IInstallableUnit> iterator = updatesAvailable.iterator(); iterator.hasNext();) {
			availableUpdates.add(iterator.next());
		}
		return availableUpdates;
	}

	//Create an OR expression that is matching all the entries from the given collection
	private IRequirement createORRequirement(Collection<IInstallableUnit> findUpdates, boolean optional) {
		StringBuffer expression = new StringBuffer();
		Object[] expressionParameters = new Object[findUpdates.size() * 2];
		int count = 0;
		for (IInstallableUnit iu : findUpdates) {
			expression.append("(id == $").append(count * 2).append(" && version == $").append(count * 2 + 1).append(')'); //$NON-NLS-1$//$NON-NLS-2$
			if (findUpdates.size() > 1 && count < findUpdates.size() - 1)
				expression.append(" || "); //$NON-NLS-1$
			expressionParameters[count * 2] = iu.getId();
			expressionParameters[count * 2 + 1] = iu.getVersion();
			count++;
		}
		IMatchExpression<IInstallableUnit> iuMatcher = ExpressionUtil.getFactory().<IInstallableUnit> matchExpression(ExpressionUtil.parse(expression.toString()), expressionParameters);
		return MetadataFactory.createRequirement(iuMatcher, null, optional ? 0 : 1, 1, true);
	}

	//Loosen up the IUs that are already part of the profile
	//Given how we are creating our request, this needs to take into account the removal from the original request as well as the change in inclusion 
	private IProfileChangeRequest loosenUpInstalledSoftware(IProfileChangeRequest request, IProfileChangeRequest originalRequest) {
		IQueryResult<IInstallableUnit> allRoots = profile.query(new IUProfilePropertyQuery(INCLUSION_RULES, IUProfilePropertyQuery.ANY), null);

		for (IInstallableUnit existingIU : allRoots) {
			Collection<IInstallableUnit> potentialUpdates = allowInstalledUpdate ? findUpdates(existingIU) : new HashSet();
			foundDifferentVersionsForElementsInstalled = (foundDifferentVersionsForElementsInstalled || (potentialUpdates.size() == 0 ? false : true));
			potentialUpdates.add(existingIU);
			Collection<IRequirement> newRequirement = new ArrayList<IRequirement>(1);
			//when the element is requested for removal or is installed optionally we make sure to mark it optional, otherwise the removal woudl fail
			IRequirement req = createORRequirement(potentialUpdates, allowInstalledRemoval || removalRequested(existingIU, originalRequest) || isOptionallyInstalled(existingIU, originalRequest));
			newRequirement.add(req);
			request.addExtraRequirements(newRequirement);
			requirementsForElementsAlreadyInstalled.addAll(newRequirement);
			request.remove(existingIU);
			rememberIUProfileProperties(existingIU, req, originalRequest, true);
		}

		return request;
	}

	//This return whether or not the given IU is installed optionally or not.
	//This also take into account the future state
	private boolean isOptionallyInstalled(IInstallableUnit existingIU, IProfileChangeRequest request) {
		return computeFutureStateOfInclusion((ProfileChangeRequest) request).contains(existingIU);
	}

	//Given the change request, this returns the collection of optional IUs 
	private Set<IInstallableUnit> computeFutureStateOfInclusion(ProfileChangeRequest profileChangeRequest) {
		if (futureOptionalIUs != null)
			return futureOptionalIUs;

		futureOptionalIUs = profileChangeRequest.getProfile().query(new IUProfilePropertyQuery(INCLUSION_RULES, INCLUSION_OPTIONAL), null).toSet();

		Set<Entry<IInstallableUnit, List<String>>> propertiesBeingRemoved = profileChangeRequest.getInstallableUnitProfilePropertiesToRemove().entrySet();
		for (Entry<IInstallableUnit, List<String>> propertyRemoved : propertiesBeingRemoved) {
			if (propertyRemoved.getValue().contains(INCLUSION_RULES)) {
				futureOptionalIUs.remove(propertyRemoved.getKey());
			}
		}

		Set<Entry<IInstallableUnit, Map<String, String>>> propertiesBeingAdded = profileChangeRequest.getInstallableUnitProfilePropertiesToAdd().entrySet();
		for (Entry<IInstallableUnit, Map<String, String>> propertyBeingAdded : propertiesBeingAdded) {
			String inclusionRule = propertyBeingAdded.getValue().get(INCLUSION_RULES);
			if (inclusionRule == null) {
				continue;
			}
			if (INCLUSION_STRICT.equals(inclusionRule)) {
				futureOptionalIUs.remove(propertyBeingAdded.getKey());
			}
			if (INCLUSION_OPTIONAL.equals(inclusionRule)) {
				futureOptionalIUs.add(propertyBeingAdded.getKey());
			}
		}
		return futureOptionalIUs;

	}
}

Back to the top