| 1 |
/******************************************************************************* |
| 2 |
* Copyright (c) 2007, 2022 IBM Corporation and others. |
| 3 |
* |
| 4 |
* This |
| 5 |
* program and the accompanying materials are made available under the terms of |
| 6 |
* the Eclipse Public License 2.0 which accompanies this distribution, and is |
| 7 |
* available at |
| 8 |
* https://www.eclipse.org/legal/epl-2.0/ |
| 9 |
* |
| 10 |
* SPDX-License-Identifier: EPL-2.0 |
| 11 |
* |
| 12 |
* Contributors: |
| 13 |
* IBM Corporation - initial API and implementation |
| 14 |
* Ericsson AB - ongoing development |
| 15 |
* Red Hat, Inc. - fragments support added, Bug 460967 |
| 16 |
* Christoph Läubrich - Issue #20 - XMLParser should not require a bundle context but a Parser in the constructor |
| 17 |
******************************************************************************/ |
| 18 |
package org.eclipse.equinox.internal.p2.engine; |
| 19 |
|
| 20 |
import java.io.*; |
| 21 |
import java.lang.ref.SoftReference; |
| 22 |
import java.net.URI; |
| 23 |
import java.util.*; |
| 24 |
import java.util.Map.Entry; |
| 25 |
import java.util.zip.GZIPInputStream; |
| 26 |
import java.util.zip.GZIPOutputStream; |
| 27 |
import javax.xml.parsers.ParserConfigurationException; |
| 28 |
import org.eclipse.core.runtime.*; |
| 29 |
import org.eclipse.core.runtime.jobs.Job; |
| 30 |
import org.eclipse.equinox.internal.p2.core.helpers.*; |
| 31 |
import org.eclipse.equinox.internal.p2.metadata.TranslationSupport; |
| 32 |
import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; |
| 33 |
import org.eclipse.equinox.p2.core.*; |
| 34 |
import org.eclipse.equinox.p2.core.spi.IAgentService; |
| 35 |
import org.eclipse.equinox.p2.engine.*; |
| 36 |
import org.eclipse.equinox.p2.metadata.*; |
| 37 |
import org.eclipse.equinox.p2.query.IQueryResult; |
| 38 |
import org.eclipse.equinox.p2.query.QueryUtil; |
| 39 |
import org.eclipse.osgi.service.datalocation.Location; |
| 40 |
import org.eclipse.osgi.util.NLS; |
| 41 |
import org.osgi.framework.BundleContext; |
| 42 |
import org.osgi.framework.ServiceReference; |
| 43 |
import org.xml.sax.*; |
| 44 |
|
| 45 |
public class SimpleProfileRegistry implements IProfileRegistry, IAgentService { |
| 46 |
|
| 47 |
private static final String SIMPLE_PROFILE_REGISTRY_INTERNAL = "_simpleProfileRegistry_internal_"; //$NON-NLS-1$ |
| 48 |
private static final String PROFILE_REGISTRY = "profile registry"; //$NON-NLS-1$ |
| 49 |
private static final String PROFILE_PROPERTIES_FILE = "state.properties"; //$NON-NLS-1$ |
| 50 |
|
| 51 |
private static final String PROFILE_EXT = ".profile"; //$NON-NLS-1$ |
| 52 |
private static final String PROFILE_GZ_EXT = ".profile.gz"; //$NON-NLS-1$ |
| 53 |
public static final String DEFAULT_STORAGE_DIR = "profileRegistry"; //$NON-NLS-1$ |
| 54 |
private static final String DATA_EXT = ".data"; //$NON-NLS-1$ |
| 55 |
|
| 56 |
//Internal constant used to keep track of the newly created timestamp |
| 57 |
private static final String SERVICE_SHARED_INSTALL_NEW_TIMESTAMP = IProfileRegistry.class.getName() + '_' + "NEW_SELF_TIMESTAMP"; //$NON-NLS-1$ |
| 58 |
|
| 59 |
private static long lastTimeMillis = System.currentTimeMillis(); |
| 60 |
|
| 61 |
protected final IProvisioningAgent agent; |
| 62 |
|
| 63 |
/** |
| 64 |
* Reference to Map of String(Profile id)->Profile. |
| 65 |
*/ |
| 66 |
private SoftReference<Map<String, Profile>> profiles; |
| 67 |
private Map<String, ProfileLock> profileLocks = new HashMap<>(); |
| 68 |
|
| 69 |
private String self; |
| 70 |
|
| 71 |
//Whether the registry should update the self profile when the registry is restored |
| 72 |
private boolean updateSelfProfile; |
| 73 |
|
| 74 |
private File store; |
| 75 |
|
| 76 |
ISurrogateProfileHandler surrogateProfileHandler; |
| 77 |
|
| 78 |
private IProvisioningEventBus eventBus; |
| 79 |
// cache of last accessed profile state properties |
| 80 |
private ProfileStateProperties lastAccessedProperties; |
| 81 |
|
| 82 |
public SimpleProfileRegistry(IProvisioningAgent agent, File registryDirectory) { |
| 83 |
this(agent, registryDirectory, new SurrogateProfileHandler(agent), true); |
| 84 |
} |
| 85 |
|
| 86 |
public SimpleProfileRegistry(IProvisioningAgent agent, File registryDirectory, ISurrogateProfileHandler handler, boolean updateSelfProfile) { |
| 87 |
this.agent = agent; |
| 88 |
store = registryDirectory; |
| 89 |
surrogateProfileHandler = handler; |
| 90 |
Assert.isNotNull(store, "Profile registry requires a directory"); //$NON-NLS-1$ |
| 91 |
findSelf(); |
| 92 |
this.updateSelfProfile = updateSelfProfile; |
| 93 |
} |
| 94 |
|
| 95 |
/** |
| 96 |
* Determine the id of the "self" profile. This is only applicable for the registry |
| 97 |
* of the currently running system. |
| 98 |
*/ |
| 99 |
private void findSelf() { |
| 100 |
//the location for the currently running system is registered as a service |
| 101 |
final BundleContext context = EngineActivator.getContext(); |
| 102 |
if (context == null) |
| 103 |
return; |
| 104 |
ServiceReference<IAgentLocation> ref = context.getServiceReference(IAgentLocation.class); |
| 105 |
if (ref == null) |
| 106 |
return; |
| 107 |
IAgentLocation location = context.getService(ref); |
| 108 |
if (location == null) |
| 109 |
return; |
| 110 |
if (store.equals(getDefaultRegistryDirectory(location))) { |
| 111 |
//we are the registry for the currently running system |
| 112 |
self = context.getProperty("eclipse.p2.profile"); //$NON-NLS-1$ |
| 113 |
} else if (agent.getService(IProvisioningAgent.SHARED_CURRENT_AGENT) != null) { |
| 114 |
// In shared mode, _SELF_ is the value of the current running profile for both agents current and shared |
| 115 |
if (((IProvisioningAgent) agent.getService(IProvisioningAgent.SHARED_CURRENT_AGENT)).getService(IProvisioningAgent.SHARED_BASE_AGENT) == agent) { |
| 116 |
self = context.getProperty("eclipse.p2.profile"); //$NON-NLS-1$ |
| 117 |
} |
| 118 |
} |
| 119 |
if (self == null) |
| 120 |
self = (String) agent.getService("FORCED_SELF"); //$NON-NLS-1$ |
| 121 |
context.ungetService(ref); |
| 122 |
} |
| 123 |
|
| 124 |
public static File getDefaultRegistryDirectory(IAgentLocation agent) { |
| 125 |
File registryDirectory = null; |
| 126 |
if (agent == null) |
| 127 |
throw new IllegalStateException("Profile Registry inialization failed: Agent Location is not available"); //$NON-NLS-1$ |
| 128 |
final URI engineDataArea = agent.getDataArea(EngineActivator.ID); |
| 129 |
URI registryURL = URIUtil.append(engineDataArea, DEFAULT_STORAGE_DIR); |
| 130 |
registryDirectory = new File(registryURL); |
| 131 |
registryDirectory.mkdirs(); |
| 132 |
return registryDirectory; |
| 133 |
} |
| 134 |
|
| 135 |
/** |
| 136 |
* If the current profile for self is marked as a roaming profile, we need |
| 137 |
* to update its install and bundle pool locations. |
| 138 |
*/ |
| 139 |
private void updateSelfProfile(Map<String, Profile> profileMap) { |
| 140 |
if (profileMap == null) |
| 141 |
return; |
| 142 |
Profile selfProfile = profileMap.get(self); |
| 143 |
if (selfProfile == null) |
| 144 |
return; |
| 145 |
|
| 146 |
//register default locale provider where metadata translations are found |
| 147 |
//TODO ideally this should not be hard-coded to the current profile |
| 148 |
TranslationSupport.getInstance().setTranslationSource(selfProfile); |
| 149 |
|
| 150 |
if (DebugHelper.DEBUG_PROFILE_REGISTRY) |
| 151 |
DebugHelper.debug(PROFILE_REGISTRY, "SimpleProfileRegistry.updateSelfProfile"); //$NON-NLS-1$ |
| 152 |
boolean changed = false; |
| 153 |
//only update if self is a roaming profile |
| 154 |
if (Boolean.parseBoolean(selfProfile.getProperty(IProfile.PROP_ROAMING))) |
| 155 |
changed = updateRoamingProfile(selfProfile); |
| 156 |
|
| 157 |
if (changed) |
| 158 |
saveProfile(selfProfile); |
| 159 |
} |
| 160 |
|
| 161 |
private boolean updateRoamingProfile(Profile selfProfile) { |
| 162 |
if (DebugHelper.DEBUG_PROFILE_REGISTRY) |
| 163 |
DebugHelper.debug(PROFILE_REGISTRY, "SimpleProfileRegistry.updateRoamingProfile"); //$NON-NLS-1$ |
| 164 |
Location installLocation = ServiceHelper.getService(EngineActivator.getContext(), Location.class, Location.INSTALL_FILTER); |
| 165 |
File location = URLUtil.toFile(installLocation.getURL()); |
| 166 |
if (location == null) { |
| 167 |
// fallback: use only path of the URL if the protocol is not 'file' |
| 168 |
location = new File(installLocation.getURL().getPath()); |
| 169 |
} |
| 170 |
boolean changed = false; |
| 171 |
if (!location.equals(new File(selfProfile.getProperty(IProfile.PROP_INSTALL_FOLDER)))) { |
| 172 |
selfProfile.setProperty(IProfile.PROP_INSTALL_FOLDER, location.getAbsolutePath()); |
| 173 |
changed = true; |
| 174 |
} |
| 175 |
String propCache = selfProfile.getProperty(IProfile.PROP_CACHE); |
| 176 |
if (propCache != null && !location.equals(new File(propCache))) { |
| 177 |
selfProfile.setProperty(IProfile.PROP_CACHE, location.getAbsolutePath()); |
| 178 |
changed = true; |
| 179 |
} |
| 180 |
if (DebugHelper.DEBUG_PROFILE_REGISTRY) |
| 181 |
DebugHelper.debug(PROFILE_REGISTRY, "SimpleProfileRegistry.updateRoamingProfile(changed=" + changed + ')'); //$NON-NLS-1$ |
| 182 |
return changed; |
| 183 |
} |
| 184 |
|
| 185 |
@Override |
| 186 |
public synchronized String toString() { |
| 187 |
return "Profile registry for location: " + store.getAbsolutePath() + "\n" + getProfileMap().toString(); //$NON-NLS-1$ //$NON-NLS-2$ |
| 188 |
} |
| 189 |
|
| 190 |
@Override |
| 191 |
public synchronized IProfile getProfile(String id) { |
| 192 |
Profile profile = internalGetProfile(id); |
| 193 |
if (profile == null) |
| 194 |
return null; |
| 195 |
return profile.snapshot(); |
| 196 |
} |
| 197 |
|
| 198 |
@Override |
| 199 |
public synchronized IProfile getProfile(String id, long timestamp) { |
| 200 |
if (SELF.equals(id)) |
| 201 |
id = self; |
| 202 |
|
| 203 |
if (profiles != null) { |
| 204 |
IProfile profile = getProfile(id); |
| 205 |
if (profile != null && profile.getTimestamp() == timestamp) |
| 206 |
return profile; |
| 207 |
} |
| 208 |
|
| 209 |
File profileDirectory = getProfileFolder(id); |
| 210 |
if (!profileDirectory.isDirectory()) |
| 211 |
return null; |
| 212 |
|
| 213 |
File profileFile = new File(profileDirectory, Long.toString(timestamp) + PROFILE_GZ_EXT); |
| 214 |
if (!profileFile.exists()) { |
| 215 |
profileFile = new File(profileDirectory, Long.toString(timestamp) + PROFILE_EXT); |
| 216 |
if (!profileFile.exists()) |
| 217 |
return null; |
| 218 |
} |
| 219 |
|
| 220 |
Parser parser = new Parser(EngineActivator.ID); |
| 221 |
try { |
| 222 |
parser.parse(profileFile); |
| 223 |
} catch (IOException e) { |
| 224 |
LogHelper.log(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.error_parsing_profile, profileFile), e)); |
| 225 |
} |
| 226 |
return parser.getProfileMap().get(id); |
| 227 |
} |
| 228 |
|
| 229 |
@Override |
| 230 |
public synchronized long[] listProfileTimestamps(String id) { |
| 231 |
if (SELF.equals(id)) |
| 232 |
id = self; |
| 233 |
//guard against null self profile |
| 234 |
if (id == null) |
| 235 |
return new long[0]; |
| 236 |
|
| 237 |
File profileDirectory = getProfileFolder(id); |
| 238 |
if (!profileDirectory.isDirectory()) |
| 239 |
return new long[0]; |
| 240 |
|
| 241 |
File[] profileFiles = profileDirectory.listFiles((FileFilter) pathname -> (pathname.getName().endsWith(PROFILE_EXT) || pathname.getName().endsWith(PROFILE_GZ_EXT)) && pathname.isFile() && !pathname.getName().startsWith("._")); |
| 242 |
|
| 243 |
long[] timestamps = new long[profileFiles.length]; |
| 244 |
for (int i = 0; i < profileFiles.length; i++) { |
| 245 |
String filename = profileFiles[i].getName(); |
| 246 |
int extensionIndex = filename.lastIndexOf(PROFILE_EXT); |
| 247 |
try { |
| 248 |
timestamps[i] = Long.parseLong(filename.substring(0, extensionIndex)); |
| 249 |
} catch (NumberFormatException e) { |
| 250 |
throw new IllegalStateException("Incompatible profile file name. Expected format is {timestamp}" + PROFILE_GZ_EXT + " (or {timestamp}" + PROFILE_EXT + ") but was " + filename + "."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ |
| 251 |
} |
| 252 |
} |
| 253 |
Arrays.sort(timestamps); |
| 254 |
return timestamps; |
| 255 |
} |
| 256 |
|
| 257 |
/** |
| 258 |
* Returns the profile with the given ID, or {@code null} if no such profile exists. |
| 259 |
*/ |
| 260 |
private Profile internalGetProfile(String id) { |
| 261 |
if (SELF.equals(id)) |
| 262 |
id = self; |
| 263 |
Profile profile = getProfileMap().get(id); |
| 264 |
if (self != null && self.equals(id)) { |
| 265 |
boolean resetProfile = false; |
| 266 |
if (profile != null && ignoreExistingProfile(profile)) { |
| 267 |
internalSetProfileStateProperty(profile, profile.getTimestamp(), IProfile.STATE_PROP_SHARED_INSTALL, IProfile.STATE_SHARED_INSTALL_VALUE_BEFOREFLUSH); |
| 268 |
profile = null; |
| 269 |
resetProfile = true; |
| 270 |
} |
| 271 |
if (profile == null) { |
| 272 |
profile = createSurrogateProfile(id); |
| 273 |
if (profile == null) |
| 274 |
return null; |
| 275 |
|
| 276 |
if (resetProfile) { |
| 277 |
//Now that we created a new profile. Tag it, override the property and register the timestamp in the agent registry for pickup by other |
| 278 |
internalSetProfileStateProperty(profile, profile.getTimestamp(), IProfile.STATE_PROP_SHARED_INSTALL, IProfile.STATE_SHARED_INSTALL_VALUE_NEW); |
| 279 |
internalSetProfileStateProperty(profile, profile.getTimestamp(), SIMPLE_PROFILE_REGISTRY_INTERNAL + getBaseTimestamp(profile.getProfileId()), getBaseTimestamp(id)); |
| 280 |
//fragments support - remeber the property |
| 281 |
internalSetProfileStateProperty(profile, profile.getTimestamp(), SIMPLE_PROFILE_REGISTRY_INTERNAL + getExtTimeStamp(), getExtTimeStamp()); |
| 282 |
agent.registerService(SERVICE_SHARED_INSTALL_NEW_TIMESTAMP, Long.toString(profile.getTimestamp())); |
| 283 |
} else { |
| 284 |
//This is the first time we create the shared profile. Tag it as such and also remember the timestamp of the base |
| 285 |
internalSetProfileStateProperty(profile, profile.getTimestamp(), IProfile.STATE_PROP_SHARED_INSTALL, IProfile.STATE_SHARED_INSTALL_VALUE_INITIAL); |
| 286 |
String baseTimestamp = getBaseTimestamp(id); |
| 287 |
if (baseTimestamp != null) |
| 288 |
internalSetProfileStateProperty(profile, profile.getTimestamp(), SIMPLE_PROFILE_REGISTRY_INTERNAL + baseTimestamp, baseTimestamp); |
| 289 |
String extTimestamp = getExtTimeStamp(); |
| 290 |
internalSetProfileStateProperty(profile, profile.getTimestamp(), SIMPLE_PROFILE_REGISTRY_INTERNAL + extTimestamp, extTimestamp); |
| 291 |
} |
| 292 |
} |
| 293 |
} |
| 294 |
return profile; |
| 295 |
} |
| 296 |
|
| 297 |
// get timestamp of fragments (extensions) |
| 298 |
private String getExtTimeStamp() { |
| 299 |
long result = -1; |
| 300 |
if (!EngineActivator.EXTENDED) { |
| 301 |
return Long.toString(result); |
| 302 |
} |
| 303 |
File[] extensions = EngineActivator.getExtensionsDirectories(); |
| 304 |
for (File extension : extensions) { |
| 305 |
if (extension.lastModified() > result) { |
| 306 |
result = extension.lastModified(); |
| 307 |
} |
| 308 |
} |
| 309 |
return Long.toString(result); |
| 310 |
} |
| 311 |
|
| 312 |
private boolean ignoreExistingProfile(IProfile profile) { |
| 313 |
if (agent.getService(SERVICE_SHARED_INSTALL_NEW_TIMESTAMP) != null) |
| 314 |
return false; |
| 315 |
|
| 316 |
String baseTimestamp = getBaseTimestamp(profile.getProfileId()); |
| 317 |
String extTimestamp = getExtTimeStamp(); |
| 318 |
if (baseTimestamp == null) { |
| 319 |
return false; |
| 320 |
} |
| 321 |
|
| 322 |
boolean extensionOK = true; |
| 323 |
if (surrogateProfileHandler != null && surrogateProfileHandler.isSurrogate(profile)) { |
| 324 |
extensionOK = (internalGetProfileStateProperties(profile, SIMPLE_PROFILE_REGISTRY_INTERNAL + extTimestamp, false).size() != 0); |
| 325 |
} |
| 326 |
|
| 327 |
if ((internalGetProfileStateProperties(profile, SIMPLE_PROFILE_REGISTRY_INTERNAL + baseTimestamp, false).size() != 0) && extensionOK) |
| 328 |
return false; |
| 329 |
|
| 330 |
return true; |
| 331 |
} |
| 332 |
|
| 333 |
private String getBaseTimestamp(String id) { |
| 334 |
IProvisioningAgent baseAgent = (IProvisioningAgent) agent.getService(IProvisioningAgent.SHARED_BASE_AGENT); |
| 335 |
if (baseAgent == null) |
| 336 |
return null; |
| 337 |
IProfileRegistry registry = baseAgent.getService(IProfileRegistry.class); |
| 338 |
if (registry == null) |
| 339 |
return null; |
| 340 |
long[] revisions = registry.listProfileTimestamps(id); |
| 341 |
if (revisions.length >= 1) { |
| 342 |
return Long.toString(revisions[revisions.length - 1]); |
| 343 |
} |
| 344 |
return null; |
| 345 |
} |
| 346 |
|
| 347 |
private Profile createSurrogateProfile(String id) { |
| 348 |
if (surrogateProfileHandler == null) |
| 349 |
return null; |
| 350 |
|
| 351 |
Profile profile = (Profile) surrogateProfileHandler.createProfile(id); |
| 352 |
if (profile == null) |
| 353 |
return null; |
| 354 |
|
| 355 |
saveProfile(profile); |
| 356 |
resetProfiles(); |
| 357 |
return getProfileMap().get(id); |
| 358 |
} |
| 359 |
|
| 360 |
@Override |
| 361 |
public synchronized IProfile[] getProfiles() { |
| 362 |
Map<String, Profile> profileMap = getProfileMap(); |
| 363 |
Profile[] result = new Profile[profileMap.size()]; |
| 364 |
int i = 0; |
| 365 |
for (Profile profile : profileMap.values()) { |
| 366 |
result[i++] = profile.snapshot(); |
| 367 |
} |
| 368 |
return result; |
| 369 |
} |
| 370 |
|
| 371 |
/** |
| 372 |
* Returns an initialized map of String(Profile id)->Profile. |
| 373 |
*/ |
| 374 |
protected Map<String, Profile> getProfileMap() { |
| 375 |
if (profiles != null) { |
| 376 |
Map<String, Profile> result = profiles.get(); |
| 377 |
if (result != null) |
| 378 |
return result; |
| 379 |
} |
| 380 |
Map<String, Profile> result = restore(); |
| 381 |
if (result == null) |
| 382 |
result = new LinkedHashMap<>(8); |
| 383 |
profiles = new SoftReference<>(result); |
| 384 |
if (updateSelfProfile) { |
| 385 |
//update self profile on first load |
| 386 |
updateSelfProfile(result); |
| 387 |
} |
| 388 |
return result; |
| 389 |
} |
| 390 |
|
| 391 |
public synchronized void updateProfile(Profile profile) { |
| 392 |
String id = profile.getProfileId(); |
| 393 |
Profile current = getProfileMap().get(id); |
| 394 |
if (current == null) |
| 395 |
throw new IllegalArgumentException(NLS.bind(Messages.profile_does_not_exist, id)); |
| 396 |
|
| 397 |
ProfileLock lock = profileLocks.get(id); |
| 398 |
lock.checkLocked(); |
| 399 |
|
| 400 |
current.clearLocalProperties(); |
| 401 |
current.clearInstallableUnits(); |
| 402 |
|
| 403 |
current.addProperties(profile.getLocalProperties()); |
| 404 |
IQueryResult<IInstallableUnit> queryResult = profile.query(QueryUtil.createIUAnyQuery(), null); |
| 405 |
for (IInstallableUnit iu : queryResult) { |
| 406 |
current.addInstallableUnit(iu); |
| 407 |
Map<String, String> iuProperties = profile.getInstallableUnitProperties(iu); |
| 408 |
if (iuProperties != null) |
| 409 |
current.addInstallableUnitProperties(iu, iuProperties); |
| 410 |
} |
| 411 |
saveProfile(current); |
| 412 |
profile.clearOrphanedInstallableUnitProperties(); |
| 413 |
profile.setTimestamp(current.getTimestamp()); |
| 414 |
broadcastChangeEvent(id, IProfileEvent.CHANGED); |
| 415 |
} |
| 416 |
|
| 417 |
@Override |
| 418 |
public IProfile addProfile(String id) throws ProvisionException { |
| 419 |
return addProfile(id, null, null); |
| 420 |
} |
| 421 |
|
| 422 |
@Override |
| 423 |
public IProfile addProfile(String id, Map<String, String> profileProperties) throws ProvisionException { |
| 424 |
return addProfile(id, profileProperties, null); |
| 425 |
} |
| 426 |
|
| 427 |
public synchronized IProfile addProfile(String id, Map<String, String> profileProperties, String parentId) throws ProvisionException { |
| 428 |
if (SELF.equals(id)) |
| 429 |
id = self; |
| 430 |
Map<String, Profile> profileMap = getProfileMap(); |
| 431 |
if (profileMap.get(id) != null) |
| 432 |
throw new ProvisionException(NLS.bind(Messages.Profile_Duplicate_Root_Profile_Id, id)); |
| 433 |
|
| 434 |
Profile parent = null; |
| 435 |
if (parentId != null) { |
| 436 |
if (SELF.equals(parentId)) |
| 437 |
parentId = self; |
| 438 |
parent = profileMap.get(parentId); |
| 439 |
if (parent == null) |
| 440 |
throw new ProvisionException(NLS.bind(Messages.Profile_Parent_Not_Found, parentId)); |
| 441 |
} |
| 442 |
|
| 443 |
Profile profile = new Profile(agent, id, parent, profileProperties); |
| 444 |
if (surrogateProfileHandler != null && surrogateProfileHandler.isSurrogate(profile)) |
| 445 |
profile.setSurrogateProfileHandler(surrogateProfileHandler); |
| 446 |
profileMap.put(id, profile); |
| 447 |
saveProfile(profile); |
| 448 |
broadcastChangeEvent(id, IProfileEvent.ADDED); |
| 449 |
return profile.snapshot(); |
| 450 |
} |
| 451 |
|
| 452 |
@Override |
| 453 |
public synchronized void removeProfile(String profileId) { |
| 454 |
if (SELF.equals(profileId)) |
| 455 |
profileId = self; |
| 456 |
//note we need to maintain a reference to the profile map until it is persisted to prevent gc |
| 457 |
Map<String, Profile> profileMap = getProfileMap(); |
| 458 |
Profile profile = profileMap.get(profileId); |
| 459 |
if (profile == null) |
| 460 |
return; |
| 461 |
|
| 462 |
List<String> subProfileIds = profile.getSubProfileIds(); |
| 463 |
for (String subProfileId : subProfileIds) { |
| 464 |
removeProfile(subProfileId); |
| 465 |
} |
| 466 |
internalLockProfile(profile); |
| 467 |
// The above call recursively locked the parent(s). So save it away to rewind the locking process. |
| 468 |
IProfile savedParent = profile.getParentProfile(); |
| 469 |
try { |
| 470 |
profile.setParent(null); |
| 471 |
} finally { |
| 472 |
internalUnlockProfile(profile); |
| 473 |
// The above call will not recurse since parent is now null. So do it explicitly. |
| 474 |
if (savedParent != null) { |
| 475 |
internalUnlockProfile(savedParent); |
| 476 |
} |
| 477 |
} |
| 478 |
profileMap.remove(profileId); |
| 479 |
profileLocks.remove(profileId); |
| 480 |
// deleting the profile removes the folder and subsequently all |
| 481 |
// the profile state properties as well since they are stored in a file in the folder. |
| 482 |
deleteProfile(profileId); |
| 483 |
broadcastChangeEvent(profileId, IProfileEvent.REMOVED); |
| 484 |
} |
| 485 |
|
| 486 |
@Override |
| 487 |
public synchronized void removeProfile(String id, long timestamp) throws ProvisionException { |
| 488 |
if (SELF.equals(id)) |
| 489 |
id = self; |
| 490 |
|
| 491 |
if (profiles != null) { |
| 492 |
IProfile profile = getProfile(id); |
| 493 |
if (profile != null && profile.getTimestamp() == timestamp) |
| 494 |
throw new ProvisionException( |
| 495 |
NLS.bind(Messages.SimpleProfileRegistry_CannotRemoveCurrentSnapshot, profile)); |
| 496 |
} |
| 497 |
|
| 498 |
File profileDirectory = getProfileFolder(id); |
| 499 |
if (!profileDirectory.isDirectory()) |
| 500 |
return; |
| 501 |
|
| 502 |
File profileFile = new File(profileDirectory, Long.toString(timestamp) + PROFILE_GZ_EXT); |
| 503 |
if (!profileFile.exists()) { |
| 504 |
profileFile = new File(profileDirectory, Long.toString(timestamp) + PROFILE_EXT); |
| 505 |
if (!profileFile.exists()) |
| 506 |
return; |
| 507 |
} |
| 508 |
FileUtils.deleteAll(profileFile); |
| 509 |
// Ignore the return value here. If there was a problem removing the profile state |
| 510 |
// properties we don't want to fail the whole operation since the profile state itself |
| 511 |
// was removed successfully |
| 512 |
removeProfileStateProperties(id, timestamp, null); |
| 513 |
} |
| 514 |
|
| 515 |
private void broadcastChangeEvent(String profileId, int reason) { |
| 516 |
if (eventBus != null) |
| 517 |
eventBus.publishEvent(new ProfileEvent(profileId, reason)); |
| 518 |
} |
| 519 |
|
| 520 |
/** |
| 521 |
* Restores the profile registry from disk, and returns the loaded profile map. |
| 522 |
* Returns <code>null</code> if unable to read the registry. |
| 523 |
*/ |
| 524 |
private Map<String, Profile> restore() { |
| 525 |
if (store == null || !store.isDirectory()) |
| 526 |
throw new IllegalStateException(NLS.bind(Messages.reg_dir_not_available, store)); |
| 527 |
|
| 528 |
Parser parser = new Parser(EngineActivator.ID); |
| 529 |
File[] profileDirectories = store.listFiles((FileFilter) pathname -> pathname.getName().endsWith(PROFILE_EXT) && pathname.isDirectory()); |
| 530 |
// protect against NPE |
| 531 |
if (profileDirectories == null) { |
| 532 |
parser.getProfileMap(); |
| 533 |
return Collections.emptyMap(); |
| 534 |
} |
| 535 |
for (File profileDirectorie : profileDirectories) { |
| 536 |
String directoryName = profileDirectorie.getName(); |
| 537 |
String profileId = unescape(directoryName.substring(0, directoryName.lastIndexOf(PROFILE_EXT))); |
| 538 |
ProfileLock lock = profileLocks.get(profileId); |
| 539 |
if (lock == null) { |
| 540 |
lock = new ProfileLock(this, profileDirectorie); |
| 541 |
profileLocks.put(profileId, lock); |
| 542 |
} |
| 543 |
|
| 544 |
boolean locked = false; |
| 545 |
if (lock.processHoldsLock() || (locked = lock.lock())) { |
| 546 |
try { |
| 547 |
File profileFile = findLatestProfileFile(profileDirectorie); |
| 548 |
if (profileFile != null) { |
| 549 |
try { |
| 550 |
parser.parse(profileFile); |
| 551 |
} catch (IOException e) { |
| 552 |
LogHelper.log(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.error_parsing_profile, profileFile), e)); |
| 553 |
} |
| 554 |
} |
| 555 |
} finally { |
| 556 |
if (locked) |
| 557 |
lock.unlock(); |
| 558 |
} |
| 559 |
} else { |
| 560 |
// could not lock the profile, so add a place holder |
| 561 |
parser.addProfilePlaceHolder(profileId); |
| 562 |
} |
| 563 |
} |
| 564 |
return parser.getProfileMap(); |
| 565 |
} |
| 566 |
|
| 567 |
private File findLatestProfileFile(File profileDirectory) { |
| 568 |
File latest = null; |
| 569 |
long latestTimestamp = 0; |
| 570 |
File[] profileFiles = profileDirectory.listFiles((FileFilter) pathname -> (pathname.getName().endsWith(PROFILE_GZ_EXT) || pathname.getName().endsWith(PROFILE_EXT)) && !pathname.isDirectory()); |
| 571 |
// protect against NPE |
| 572 |
if (profileFiles == null) |
| 573 |
return null; |
| 574 |
for (File profileFile : profileFiles) { |
| 575 |
String fileName = profileFile.getName(); |
| 576 |
try { |
| 577 |
long timestamp = Long.parseLong(fileName.substring(0, fileName.indexOf(PROFILE_EXT))); |
| 578 |
if (timestamp > latestTimestamp) { |
| 579 |
latestTimestamp = timestamp; |
| 580 |
latest = profileFile; |
| 581 |
} |
| 582 |
} catch (NumberFormatException e) { |
| 583 |
// ignore |
| 584 |
} |
| 585 |
} |
| 586 |
return latest; |
| 587 |
} |
| 588 |
|
| 589 |
private void saveProfile(Profile profile) { |
| 590 |
File profileDirectory = getProfileFolder(profile.getProfileId()); |
| 591 |
profileDirectory.mkdir(); |
| 592 |
|
| 593 |
long previousTimestamp = profile.getTimestamp(); |
| 594 |
long currentTimestamp = currentTimeInMillis(lastTimeMillis); |
| 595 |
if (currentTimestamp <= previousTimestamp) { |
| 596 |
currentTimestamp = currentTimeInMillis(previousTimestamp); |
| 597 |
} |
| 598 |
boolean shouldGzipFile = shouldGzipFile(profile); |
| 599 |
File profileFile = new File(profileDirectory, Long.toString(currentTimestamp) + (shouldGzipFile ? PROFILE_GZ_EXT : PROFILE_EXT)); |
| 600 |
|
| 601 |
// Log a stack trace to see who is writing the profile. |
| 602 |
if (DebugHelper.DEBUG_PROFILE_REGISTRY) |
| 603 |
DebugHelper.debug(PROFILE_REGISTRY, "Saving profile to: " + profileFile.getAbsolutePath()); //$NON-NLS-1$ |
| 604 |
|
| 605 |
profile.setTimestamp(currentTimestamp); |
| 606 |
profile.setChanged(false); |
| 607 |
try (OutputStream os = shouldGzipFile |
| 608 |
? new GZIPOutputStream(new FileOutputStream(profileFile)) |
| 609 |
: new FileOutputStream(profileFile)) { |
| 610 |
Writer writer = new Writer(os); |
| 611 |
writer.writeProfile(profile); |
| 612 |
} catch (IOException e) { |
| 613 |
profile.setTimestamp(previousTimestamp); |
| 614 |
profileFile.delete(); |
| 615 |
LogHelper.log(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.error_persisting_profile, profile.getProfileId()), e)); |
| 616 |
} |
| 617 |
} |
| 618 |
|
| 619 |
/** |
| 620 |
* Returns current time in millis that is guaranteed to grow and higher as given |
| 621 |
* value |
| 622 |
*/ |
| 623 |
private static synchronized long currentTimeInMillis(long lastCurrentTime) { |
| 624 |
long newTime = Math.max(lastCurrentTime + 1, lastTimeMillis + 1); |
| 625 |
lastTimeMillis = Math.max(newTime, System.currentTimeMillis()); |
| 626 |
return lastTimeMillis; |
| 627 |
} |
| 628 |
|
| 629 |
public void setEventBus(IProvisioningEventBus bus) { |
| 630 |
this.eventBus = bus; |
| 631 |
} |
| 632 |
|
| 633 |
/** |
| 634 |
* Returns whether the profile file for the given profile should be written in gzip format. |
| 635 |
*/ |
| 636 |
private boolean shouldGzipFile(Profile profile) { |
| 637 |
//check system property controlling compression |
| 638 |
String format = EngineActivator.getContext().getProperty(EngineActivator.PROP_PROFILE_FORMAT); |
| 639 |
if (format != null && format.equals(EngineActivator.PROFILE_FORMAT_UNCOMPRESSED)) |
| 640 |
return false; |
| 641 |
|
| 642 |
//check whether the profile contains the p2 engine from 3.5.0 or earlier |
| 643 |
return profile.available(QueryUtil.createIUQuery("org.eclipse.equinox.p2.engine", VersionRange.create("[0.0.0, 1.0.101)")), null).isEmpty(); //$NON-NLS-1$//$NON-NLS-2$ |
| 644 |
} |
| 645 |
|
| 646 |
private void deleteProfile(String profileId) { |
| 647 |
File profileDirectory = getProfileFolder(profileId); |
| 648 |
FileUtils.deleteAll(profileDirectory); |
| 649 |
} |
| 650 |
|
| 651 |
/** |
| 652 |
* Converts a profile id into a string that can be used as a file name in any file system. |
| 653 |
*/ |
| 654 |
public static String escape(String toEscape) { |
| 655 |
StringBuilder buffer = new StringBuilder(); |
| 656 |
int length = toEscape.length(); |
| 657 |
for (int i = 0; i < length; ++i) { |
| 658 |
char ch = toEscape.charAt(i); |
| 659 |
switch (ch) { |
| 660 |
case '\\' : |
| 661 |
case '/' : |
| 662 |
case ':' : |
| 663 |
case '*' : |
| 664 |
case '?' : |
| 665 |
case '"' : |
| 666 |
case '<' : |
| 667 |
case '>' : |
| 668 |
case '|' : |
| 669 |
case '%' : |
| 670 |
buffer.append("%" + (int) ch + ";"); //$NON-NLS-1$ //$NON-NLS-2$ |
| 671 |
break; |
| 672 |
default : |
| 673 |
buffer.append(ch); |
| 674 |
} |
| 675 |
} |
| 676 |
return buffer.toString(); |
| 677 |
} |
| 678 |
|
| 679 |
public static String unescape(String text) { |
| 680 |
if (text.indexOf('%') == -1) |
| 681 |
return text; |
| 682 |
|
| 683 |
StringBuilder buffer = new StringBuilder(); |
| 684 |
int length = text.length(); |
| 685 |
for (int i = 0; i < length; ++i) { |
| 686 |
char ch = text.charAt(i); |
| 687 |
if (ch == '%') { |
| 688 |
int colon = text.indexOf(';', i); |
| 689 |
if (colon == -1) |
| 690 |
throw new IllegalStateException("error unescaping the sequence at character (" + i + ") for " + text + ". Expected %{int};."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ |
| 691 |
ch = (char) Integer.parseInt(text.substring(i + 1, colon)); |
| 692 |
i = colon; |
| 693 |
} |
| 694 |
buffer.append(ch); |
| 695 |
} |
| 696 |
return buffer.toString(); |
| 697 |
} |
| 698 |
|
| 699 |
static class Writer extends ProfileWriter { |
| 700 |
|
| 701 |
public Writer(OutputStream output) { |
| 702 |
super(output, new ProcessingInstruction[] {ProcessingInstruction.makeTargetVersionInstruction(PROFILE_TARGET, ProfileXMLConstants.CURRENT_VERSION)}); |
| 703 |
} |
| 704 |
} |
| 705 |
|
| 706 |
/* |
| 707 |
* Parser for the contents of a SimpleProfileRegistry, |
| 708 |
* as written by the Writer class. |
| 709 |
*/ |
| 710 |
class Parser extends ProfileParser { |
| 711 |
private final Map<String, ProfileHandler> profileHandlers = new HashMap<>(); |
| 712 |
|
| 713 |
public Map<String, ProfileHandler> getProfileHandlers() { |
| 714 |
return Collections.unmodifiableMap(profileHandlers); |
| 715 |
} |
| 716 |
|
| 717 |
public Parser(String bundleId) { |
| 718 |
super(bundleId); |
| 719 |
} |
| 720 |
|
| 721 |
public void addProfilePlaceHolder(String profileId) { |
| 722 |
profileHandlers.put(profileId, new ProfileHandler(profileId)); |
| 723 |
} |
| 724 |
|
| 725 |
public void parse(File file) throws IOException { |
| 726 |
InputStream is; |
| 727 |
if (file.getName().endsWith(PROFILE_GZ_EXT)) { |
| 728 |
is = new BufferedInputStream(new GZIPInputStream(new FileInputStream(file))); |
| 729 |
} else { // backward compatibility. SimpleProfileRegistry doesn't write non-gzipped profiles any more. |
| 730 |
is = new BufferedInputStream(new FileInputStream(file)); |
| 731 |
} |
| 732 |
parse(is); |
| 733 |
} |
| 734 |
|
| 735 |
public synchronized void parse(InputStream stream) throws IOException { |
| 736 |
this.status = null; |
| 737 |
try { |
| 738 |
// TODO: currently not caching the parser since we make no assumptions |
| 739 |
// or restrictions on concurrent parsing |
| 740 |
XMLReader reader = getParser().getXMLReader(); |
| 741 |
ProfileHandler profileHandler = new ProfileHandler(); |
| 742 |
reader.setContentHandler(new ProfileDocHandler(PROFILE_ELEMENT, profileHandler)); |
| 743 |
reader.parse(new InputSource(stream)); |
| 744 |
profileHandlers.put(profileHandler.getProfileId(), profileHandler); |
| 745 |
} catch (SAXException e) { |
| 746 |
IOException ioException = new IOException(e.getMessage()); |
| 747 |
ioException.initCause(e); |
| 748 |
throw ioException; |
| 749 |
} catch (ParserConfigurationException e) { |
| 750 |
IOException ioException = new IOException(e.getMessage()); |
| 751 |
ioException.initCause(e); |
| 752 |
throw ioException; |
| 753 |
} finally { |
| 754 |
stream.close(); |
| 755 |
} |
| 756 |
} |
| 757 |
|
| 758 |
@Override |
| 759 |
protected Object getRootObject() { |
| 760 |
return this; |
| 761 |
} |
| 762 |
|
| 763 |
public Map<String, Profile> getProfileMap() { |
| 764 |
Map<String, Profile> profileMap = new HashMap<>(); |
| 765 |
for (String profileId : profileHandlers.keySet()) { |
| 766 |
addProfile(profileId, profileMap); |
| 767 |
} |
| 768 |
return profileMap; |
| 769 |
} |
| 770 |
|
| 771 |
private void addProfile(String profileId, Map<String, Profile> profileMap) { |
| 772 |
if (profileMap.containsKey(profileId)) |
| 773 |
return; |
| 774 |
|
| 775 |
ProfileHandler profileHandler = profileHandlers.get(profileId); |
| 776 |
Profile parentProfile = null; |
| 777 |
|
| 778 |
String parentId = profileHandler.getParentId(); |
| 779 |
if (parentId != null) { |
| 780 |
addProfile(parentId, profileMap); |
| 781 |
parentProfile = profileMap.get(parentId); |
| 782 |
} |
| 783 |
|
| 784 |
Profile profile = new Profile(agent, profileId, parentProfile, profileHandler.getProperties()); |
| 785 |
if (surrogateProfileHandler != null && surrogateProfileHandler.isSurrogate(profile)) |
| 786 |
profile.setSurrogateProfileHandler(surrogateProfileHandler); |
| 787 |
|
| 788 |
profile.setTimestamp(profileHandler.getTimestamp()); |
| 789 |
|
| 790 |
IInstallableUnit[] ius = profileHandler.getInstallableUnits(); |
| 791 |
if (ius != null) { |
| 792 |
for (IInstallableUnit iu : ius) { |
| 793 |
profile.addInstallableUnit(iu); |
| 794 |
Map<String, String> iuProperties = profileHandler.getIUProperties(iu); |
| 795 |
if (iuProperties != null) { |
| 796 |
for (Entry<String, String> entry : iuProperties.entrySet()) { |
| 797 |
profile.setInstallableUnitProperty(iu, entry.getKey(), entry.getValue()); |
| 798 |
} |
| 799 |
} |
| 800 |
} |
| 801 |
} |
| 802 |
profile.setChanged(false); |
| 803 |
profileMap.put(profileId, profile); |
| 804 |
} |
| 805 |
|
| 806 |
private final class ProfileDocHandler extends DocHandler { |
| 807 |
|
| 808 |
public ProfileDocHandler(String rootName, RootHandler rootHandler) { |
| 809 |
super(rootName, rootHandler); |
| 810 |
} |
| 811 |
|
| 812 |
@Override |
| 813 |
public void processingInstruction(String target, String data) throws SAXException { |
| 814 |
if (ProfileXMLConstants.PROFILE_TARGET.equals(target)) { |
| 815 |
Version repositoryVersion = extractPIVersion(target, data); |
| 816 |
if (!ProfileXMLConstants.XML_TOLERANCE.isIncluded(repositoryVersion)) { |
| 817 |
throw new SAXException(NLS.bind(Messages.SimpleProfileRegistry_Parser_Has_Incompatible_Version, repositoryVersion, ProfileXMLConstants.XML_TOLERANCE)); |
| 818 |
} |
| 819 |
} |
| 820 |
} |
| 821 |
} |
| 822 |
|
| 823 |
@Override |
| 824 |
protected String getErrorMessage() { |
| 825 |
return Messages.SimpleProfileRegistry_Parser_Error_Parsing_Registry; |
| 826 |
} |
| 827 |
|
| 828 |
@Override |
| 829 |
public String toString() { |
| 830 |
// TODO: |
| 831 |
return null; |
| 832 |
} |
| 833 |
|
| 834 |
} |
| 835 |
|
| 836 |
@Override |
| 837 |
public synchronized boolean isCurrent(IProfile profile) { |
| 838 |
Profile internalProfile = getProfileMap().get(profile.getProfileId()); |
| 839 |
if (internalProfile == null) |
| 840 |
throw new IllegalArgumentException(NLS.bind(Messages.profile_not_registered, profile.getProfileId())); |
| 841 |
|
| 842 |
if (!internalLockProfile(internalProfile)) |
| 843 |
throw new IllegalStateException(Messages.SimpleProfileRegistry_Profile_in_use); |
| 844 |
|
| 845 |
try { |
| 846 |
return (!((Profile) profile).isChanged() && checkTimestamps(profile, internalProfile)); |
| 847 |
} finally { |
| 848 |
internalUnlockProfile(internalProfile); |
| 849 |
} |
| 850 |
} |
| 851 |
|
| 852 |
public synchronized void lockProfile(Profile profile) { |
| 853 |
Profile internalProfile = internalGetProfile(profile.getProfileId()); |
| 854 |
if (internalProfile == null) |
| 855 |
throw new IllegalArgumentException(NLS.bind(Messages.profile_not_registered, profile.getProfileId())); |
| 856 |
|
| 857 |
if (!internalLockProfile(internalProfile)) |
| 858 |
throw new IllegalStateException(Messages.SimpleProfileRegistry_Profile_in_use); |
| 859 |
|
| 860 |
boolean isCurrent = false; |
| 861 |
try { |
| 862 |
if (profile.isChanged()) { |
| 863 |
if (DebugHelper.DEBUG_PROFILE_REGISTRY) |
| 864 |
DebugHelper.debug(PROFILE_REGISTRY, "Profile is marked as changed."); //$NON-NLS-1$ |
| 865 |
throw new IllegalStateException(NLS.bind(Messages.profile_changed, profile.getProfileId())); |
| 866 |
} |
| 867 |
if (!checkTimestamps(profile, internalProfile)) { |
| 868 |
if (DebugHelper.DEBUG_PROFILE_REGISTRY) |
| 869 |
DebugHelper.debug(PROFILE_REGISTRY, "Unexpected timestamp difference in profile."); //$NON-NLS-1$ |
| 870 |
throw new IllegalStateException(NLS.bind(Messages.profile_not_current, new String[] {profile.getProfileId(), Long.toString(internalProfile.getTimestamp()), Long.toString(profile.getTimestamp())})); |
| 871 |
} |
| 872 |
isCurrent = true; |
| 873 |
} finally { |
| 874 |
// this check is done here to ensure we unlock even if a runtime exception is thrown |
| 875 |
if (!isCurrent) |
| 876 |
internalUnlockProfile(internalProfile); |
| 877 |
} |
| 878 |
} |
| 879 |
|
| 880 |
private boolean internalLockProfile(IProfile profile) { |
| 881 |
ProfileLock lock = profileLocks.get(profile.getProfileId()); |
| 882 |
if (lock == null) { |
| 883 |
lock = new ProfileLock(this, getProfileFolder(profile.getProfileId())); |
| 884 |
profileLocks.put(profile.getProfileId(), lock); |
| 885 |
} |
| 886 |
return lock.lock(); |
| 887 |
} |
| 888 |
|
| 889 |
private boolean checkTimestamps(IProfile profile, IProfile internalProfile) { |
| 890 |
long[] timestamps = listProfileTimestamps(profile.getProfileId()); |
| 891 |
if (timestamps.length == 0) { |
| 892 |
if (DebugHelper.DEBUG_PROFILE_REGISTRY) |
| 893 |
DebugHelper.debug(PROFILE_REGISTRY, "check timestamp: expected " + profile.getTimestamp() + " but no profiles were found"); //$NON-NLS-1$ //$NON-NLS-2$ |
| 894 |
resetProfiles(); |
| 895 |
return false; |
| 896 |
} |
| 897 |
|
| 898 |
long currentTimestamp = timestamps[timestamps.length - 1]; |
| 899 |
if (profile.getTimestamp() != currentTimestamp) { |
| 900 |
if (DebugHelper.DEBUG_PROFILE_REGISTRY) |
| 901 |
DebugHelper.debug(PROFILE_REGISTRY, "check timestamp: expected " + profile.getTimestamp() + " but was " + currentTimestamp); //$NON-NLS-1$ //$NON-NLS-2$ |
| 902 |
if (internalProfile.getTimestamp() != currentTimestamp) |
| 903 |
resetProfiles(); |
| 904 |
return false; |
| 905 |
} |
| 906 |
|
| 907 |
return true; |
| 908 |
} |
| 909 |
|
| 910 |
@Override |
| 911 |
public synchronized boolean containsProfile(String id) { |
| 912 |
if (SELF.equals(id)) |
| 913 |
id = self; |
| 914 |
//null check done after self check, because self can be null |
| 915 |
if (id == null) |
| 916 |
return false; |
| 917 |
|
| 918 |
// check profiles to avoid restoring the profile registry |
| 919 |
if (profiles != null) |
| 920 |
if (getProfile(id) != null) |
| 921 |
return true; |
| 922 |
|
| 923 |
File profileDirectory = getProfileFolder(id); |
| 924 |
if (!profileDirectory.isDirectory()) |
| 925 |
return false; |
| 926 |
File[] profileFiles = profileDirectory.listFiles((FileFilter) pathname -> (pathname.getName().endsWith(PROFILE_GZ_EXT) || pathname.getName().endsWith(PROFILE_EXT)) && pathname.isFile()); |
| 927 |
return profileFiles.length > 0; |
| 928 |
} |
| 929 |
|
| 930 |
public synchronized void resetProfiles() { |
| 931 |
profiles = null; |
| 932 |
} |
| 933 |
|
| 934 |
public synchronized void unlockProfile(IProfile profile) { |
| 935 |
if (profile == null) |
| 936 |
throw new IllegalArgumentException(NLS.bind(Messages.profile_not_registered, "")); //$NON-NLS-1$ |
| 937 |
internalUnlockProfile(profile); |
| 938 |
} |
| 939 |
|
| 940 |
private void internalUnlockProfile(IProfile profile) { |
| 941 |
ProfileLock lock = profileLocks.get(profile.getProfileId()); |
| 942 |
lock.unlock(); |
| 943 |
} |
| 944 |
|
| 945 |
public Profile validate(IProfile candidate) { |
| 946 |
if (candidate instanceof Profile) |
| 947 |
return (Profile) candidate; |
| 948 |
|
| 949 |
throw new IllegalArgumentException("Profile incompatible: expected " + Profile.class.getName() + " but was " + ((candidate != null) ? candidate.getClass().getName() : "null") + "."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ |
| 950 |
} |
| 951 |
|
| 952 |
public synchronized File getProfileDataDirectory(String id) { |
| 953 |
if (SELF.equals(id)) |
| 954 |
id = self; |
| 955 |
File profileDirectory = getProfileFolder(id); |
| 956 |
File profileDataArea = new File(profileDirectory, DATA_EXT); |
| 957 |
if (!profileDataArea.isDirectory() && !profileDataArea.mkdir()) |
| 958 |
throw new IllegalStateException("Could not create profile data area " + profileDataArea.getAbsolutePath() + "for: " + id); //$NON-NLS-1$ //$NON-NLS-2$ |
| 959 |
return profileDataArea; |
| 960 |
} |
| 961 |
|
| 962 |
@Override |
| 963 |
public void start() { |
| 964 |
//nothing to do |
| 965 |
} |
| 966 |
|
| 967 |
@Override |
| 968 |
public void stop() { |
| 969 |
try { |
| 970 |
//ensure there are no more profile preference save jobs running |
| 971 |
Job.getJobManager().join(ProfilePreferences.PROFILE_SAVE_JOB_FAMILY, null); |
| 972 |
} catch (InterruptedException e) { |
| 973 |
//ignore |
| 974 |
} |
| 975 |
} |
| 976 |
|
| 977 |
// Class representing a particular instance of a profile's state properties. |
| 978 |
// Can be used for caching. |
| 979 |
class ProfileStateProperties { |
| 980 |
private String id; |
| 981 |
private File file; |
| 982 |
private long timestamp; |
| 983 |
private Properties properties; |
| 984 |
|
| 985 |
ProfileStateProperties(String id, File file, Properties properties) { |
| 986 |
this.id = id; |
| 987 |
this.file = file; |
| 988 |
this.properties = properties; |
| 989 |
this.timestamp = file.lastModified(); |
| 990 |
} |
| 991 |
|
| 992 |
// return true if the cached timestamp is the same as the one on disk |
| 993 |
boolean isCurrent() { |
| 994 |
if (!file.exists()) |
| 995 |
return true; |
| 996 |
return file.lastModified() == timestamp; |
| 997 |
} |
| 998 |
|
| 999 |
String getId() { |
| 1000 |
return id; |
| 1001 |
} |
| 1002 |
|
| 1003 |
Properties getProperties() { |
| 1004 |
return this.properties; |
| 1005 |
} |
| 1006 |
} |
| 1007 |
|
| 1008 |
/* |
| 1009 |
* Return the folder on disk associated with the profile with the given identifier. |
| 1010 |
*/ |
| 1011 |
private File getProfileFolder(String id) { |
| 1012 |
return new File(store, escape(id) + PROFILE_EXT); |
| 1013 |
} |
| 1014 |
|
| 1015 |
/* |
| 1016 |
* Read and return the state properties for the profile with the given id. |
| 1017 |
* If one does not exist, then return an empty Properties file. |
| 1018 |
* If there were problems reading the file then return throw an exception. |
| 1019 |
*/ |
| 1020 |
private Properties readStateProperties(String id) throws ProvisionException { |
| 1021 |
if (SELF.equals(id)) |
| 1022 |
id = self; |
| 1023 |
|
| 1024 |
// if the last cached value is the one we are interested in and up-to-date |
| 1025 |
// then don't bother reading from disk |
| 1026 |
if (lastAccessedProperties != null && id.equals(lastAccessedProperties.getId()) && lastAccessedProperties.isCurrent()) |
| 1027 |
return lastAccessedProperties.getProperties(); |
| 1028 |
|
| 1029 |
File profileDirectory = getProfileFolder(id); |
| 1030 |
if (!profileDirectory.isDirectory()) |
| 1031 |
throw new ProvisionException(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.SimpleProfileRegistry_Bad_profile_location, profileDirectory.getPath()))); |
| 1032 |
|
| 1033 |
File file = new File(profileDirectory, PROFILE_PROPERTIES_FILE); |
| 1034 |
Properties properties = new Properties(); |
| 1035 |
if (!file.exists()) { |
| 1036 |
lastAccessedProperties = new ProfileStateProperties(id, file, properties); |
| 1037 |
return properties; |
| 1038 |
} |
| 1039 |
try (InputStream input = new BufferedInputStream(new FileInputStream(file))) { |
| 1040 |
properties.load(input); |
| 1041 |
} catch (IOException e) { |
| 1042 |
throw new ProvisionException(new Status(IStatus.ERROR, EngineActivator.ID, Messages.SimpleProfileRegistry_States_Error_Reading_File, e)); |
| 1043 |
} |
| 1044 |
|
| 1045 |
//cache the value before we return |
| 1046 |
lastAccessedProperties = new ProfileStateProperties(id, file, properties); |
| 1047 |
return properties; |
| 1048 |
} |
| 1049 |
|
| 1050 |
/* |
| 1051 |
* Write the given state properties to disk for the specified profile. |
| 1052 |
*/ |
| 1053 |
private IStatus writeStateProperties(String id, Properties properties) { |
| 1054 |
if (SELF.equals(id)) |
| 1055 |
id = self; |
| 1056 |
|
| 1057 |
File profileDirectory = getProfileFolder(id); |
| 1058 |
File file = new File(profileDirectory, PROFILE_PROPERTIES_FILE); |
| 1059 |
Properties prunedProperties = properties; |
| 1060 |
try (OutputStream output = new BufferedOutputStream(new FileOutputStream(file));) { |
| 1061 |
prunedProperties = pruneStateProperties(id, properties); |
| 1062 |
prunedProperties.store(output, null); |
| 1063 |
output.flush(); |
| 1064 |
} catch (IOException e) { |
| 1065 |
return new Status(IStatus.ERROR, EngineActivator.ID, Messages.SimpleProfileRegistry_States_Error_Writing_File, e); |
| 1066 |
} |
| 1067 |
// cache the value |
| 1068 |
lastAccessedProperties = new ProfileStateProperties(id, file, prunedProperties); |
| 1069 |
return Status.OK_STATUS; |
| 1070 |
} |
| 1071 |
|
| 1072 |
// Only write state properties for state timestamps that still exist |
| 1073 |
// TODO: Do we want to expose this method as API? |
| 1074 |
// TODO: Do we want to run this method on every write or just after specific elapsed times since the last Prune? |
| 1075 |
private Properties pruneStateProperties(String id, Properties properties) { |
| 1076 |
Properties result = new Properties(); |
| 1077 |
long[] timestamps = listProfileTimestamps(id); |
| 1078 |
HashSet<String> timestampsSet = new HashSet<>(timestamps.length); |
| 1079 |
for (long timestamp : timestamps) { |
| 1080 |
timestampsSet.add(String.valueOf(timestamp)); |
| 1081 |
} |
| 1082 |
|
| 1083 |
Enumeration<Object> keys = properties.keys(); |
| 1084 |
while (keys.hasMoreElements()) { |
| 1085 |
String key = (String) keys.nextElement(); |
| 1086 |
int index = key.indexOf('.'); |
| 1087 |
if (index > -1) { |
| 1088 |
String timestamp = key.substring(0, index); |
| 1089 |
if (timestampsSet.contains(timestamp)) { |
| 1090 |
result.put(key, properties.get(key)); |
| 1091 |
} |
| 1092 |
} |
| 1093 |
} |
| 1094 |
return result; |
| 1095 |
} |
| 1096 |
|
| 1097 |
/* |
| 1098 |
* Ensure a profile with the given identifier has a state with the specified timestamp. Return |
| 1099 |
* a status object indicating success or failure. |
| 1100 |
*/ |
| 1101 |
private IStatus validateState(String id, long timestamp) { |
| 1102 |
long[] states = listProfileTimestamps(id); |
| 1103 |
for (long ts : states) |
| 1104 |
if (ts == timestamp) |
| 1105 |
return Status.OK_STATUS; |
| 1106 |
return new Status(IStatus.ERROR, EngineActivator.ID, (NLS.bind(Messages.SimpleProfileRegistry_state_not_found, timestamp, id))); |
| 1107 |
} |
| 1108 |
|
| 1109 |
@Override |
| 1110 |
public IStatus setProfileStateProperties(String id, long timestamp, Map<String, String> propertiesToAdd) { |
| 1111 |
if (id == null || propertiesToAdd == null) |
| 1112 |
throw new NullPointerException(); |
| 1113 |
|
| 1114 |
Profile internalProfile = internalGetProfile(id); |
| 1115 |
if (internalProfile == null) |
| 1116 |
throw new IllegalArgumentException(id); |
| 1117 |
return internalSetProfileStateProperties(internalProfile, timestamp, propertiesToAdd); |
| 1118 |
} |
| 1119 |
|
| 1120 |
private IStatus internalSetProfileStateProperties(IProfile profile, long timestamp, Map<String, String> propertiesToAdd) { |
| 1121 |
IStatus result = validateState(profile.getProfileId(), timestamp); |
| 1122 |
if (!result.isOK()) |
| 1123 |
return result; |
| 1124 |
|
| 1125 |
if (!internalLockProfile(profile)) |
| 1126 |
throw new IllegalStateException(Messages.SimpleProfileRegistry_Profile_in_use); |
| 1127 |
|
| 1128 |
try { |
| 1129 |
Properties properties = readStateProperties(profile.getProfileId()); |
| 1130 |
for (Map.Entry<String, String> entry : propertiesToAdd.entrySet()) { |
| 1131 |
// property key format is timestamp.key |
| 1132 |
properties.put(timestamp + "." + entry.getKey(), entry.getValue()); //$NON-NLS-1$ |
| 1133 |
} |
| 1134 |
writeStateProperties(profile.getProfileId(), properties); |
| 1135 |
} catch (ProvisionException e) { |
| 1136 |
return e.getStatus(); |
| 1137 |
} finally { |
| 1138 |
internalUnlockProfile(profile); |
| 1139 |
} |
| 1140 |
return Status.OK_STATUS; |
| 1141 |
} |
| 1142 |
|
| 1143 |
@Override |
| 1144 |
public IStatus setProfileStateProperty(String id, long timestamp, String key, String value) { |
| 1145 |
if (id == null) |
| 1146 |
throw new NullPointerException(); |
| 1147 |
Profile internalProfile = internalGetProfile(id); |
| 1148 |
if (internalProfile == null) |
| 1149 |
throw new IllegalArgumentException(id); |
| 1150 |
return internalSetProfileStateProperty(internalProfile, timestamp, key, value); |
| 1151 |
} |
| 1152 |
|
| 1153 |
private IStatus internalSetProfileStateProperty(IProfile profile, long timestamp, String key, String value) { |
| 1154 |
if (key == null || value == null) |
| 1155 |
throw new NullPointerException(); |
| 1156 |
Map<String, String> properties = new HashMap<>(); |
| 1157 |
properties.put(key, value); |
| 1158 |
|
| 1159 |
return internalSetProfileStateProperties(profile, timestamp, properties); |
| 1160 |
} |
| 1161 |
|
| 1162 |
@Override |
| 1163 |
public Map<String, String> getProfileStateProperties(String id, long timestamp) { |
| 1164 |
if (id == null) |
| 1165 |
throw new NullPointerException(); |
| 1166 |
Profile internalProfile = internalGetProfile(id); |
| 1167 |
if (internalProfile == null) |
| 1168 |
return Collections.emptyMap(); |
| 1169 |
return internalGetProfileStateProperties(internalProfile, timestamp, true); |
| 1170 |
} |
| 1171 |
|
| 1172 |
private Map<String, String> internalGetProfileStateProperties(IProfile profile, long timestamp, boolean lock) { |
| 1173 |
Map<String, String> result = new HashMap<>(); |
| 1174 |
String timestampString = String.valueOf(timestamp); |
| 1175 |
int keyOffset = timestampString.length() + 1; |
| 1176 |
lock = lock || lastAccessedProperties == null; |
| 1177 |
if (lock) |
| 1178 |
if (!internalLockProfile(profile)) |
| 1179 |
throw new IllegalStateException(Messages.SimpleProfileRegistry_Profile_in_use); |
| 1180 |
try { |
| 1181 |
Properties properties = readStateProperties(profile.getProfileId()); |
| 1182 |
Iterator<Object> keys = properties.keySet().iterator(); |
| 1183 |
while (keys.hasNext()) { |
| 1184 |
String key = (String) keys.next(); |
| 1185 |
if (key.indexOf(timestampString) == 0) |
| 1186 |
result.put(key.substring(keyOffset), properties.getProperty(key)); |
| 1187 |
} |
| 1188 |
} catch (ProvisionException e) { |
| 1189 |
LogHelper.log(e); |
| 1190 |
} finally { |
| 1191 |
if (lock) |
| 1192 |
internalUnlockProfile(profile); |
| 1193 |
} |
| 1194 |
return result; |
| 1195 |
} |
| 1196 |
|
| 1197 |
@Override |
| 1198 |
public Map<String, String> getProfileStateProperties(String id, String userKey) { |
| 1199 |
if (id == null || userKey == null) |
| 1200 |
throw new NullPointerException(); |
| 1201 |
|
| 1202 |
Profile internalProfile = internalGetProfile(id); |
| 1203 |
if (internalProfile == null) |
| 1204 |
return Collections.emptyMap(); |
| 1205 |
return internalGetProfileStateProperties(internalProfile, userKey, true); |
| 1206 |
} |
| 1207 |
|
| 1208 |
private Map<String, String> internalGetProfileStateProperties(IProfile profile, String userKey, boolean lock) { |
| 1209 |
Map<String, String> result = new HashMap<>(); |
| 1210 |
lock = lock || lastAccessedProperties == null; |
| 1211 |
if (lock) |
| 1212 |
if (!internalLockProfile(profile)) |
| 1213 |
throw new IllegalStateException(Messages.SimpleProfileRegistry_Profile_in_use); |
| 1214 |
try { |
| 1215 |
Properties properties = readStateProperties(profile.getProfileId()); |
| 1216 |
Iterator<Object> keys = properties.keySet().iterator(); |
| 1217 |
while (keys.hasNext()) { |
| 1218 |
// property key format is timestamp.key |
| 1219 |
String key = (String) keys.next(); |
| 1220 |
int index = key.indexOf('.'); |
| 1221 |
if (index != -1 && index + 1 != key.length() && key.substring(index + 1).equals(userKey)) { |
| 1222 |
result.put(key.substring(0, index), properties.getProperty(key)); |
| 1223 |
} |
| 1224 |
} |
| 1225 |
} catch (ProvisionException e) { |
| 1226 |
LogHelper.log(e); |
| 1227 |
} finally { |
| 1228 |
if (lock) |
| 1229 |
internalUnlockProfile(profile); |
| 1230 |
} |
| 1231 |
return result; |
| 1232 |
} |
| 1233 |
|
| 1234 |
@Override |
| 1235 |
public IStatus removeProfileStateProperties(String id, long timestamp, Collection<String> keys) { |
| 1236 |
if (id == null) |
| 1237 |
throw new NullPointerException(); |
| 1238 |
// return if there is no work to do |
| 1239 |
if (keys != null && keys.size() == 0) |
| 1240 |
return Status.OK_STATUS; |
| 1241 |
|
| 1242 |
Profile internalProfile = internalGetProfile(id); |
| 1243 |
if (internalProfile == null) |
| 1244 |
return Status.OK_STATUS; |
| 1245 |
|
| 1246 |
if (!internalLockProfile(internalProfile)) |
| 1247 |
throw new IllegalStateException(Messages.SimpleProfileRegistry_Profile_in_use); |
| 1248 |
|
| 1249 |
try { |
| 1250 |
Properties properties = readStateProperties(id); |
| 1251 |
String timestampString = String.valueOf(timestamp); |
| 1252 |
if (keys == null) { |
| 1253 |
// remove all keys |
| 1254 |
for (Iterator<Object> already = properties.keySet().iterator(); already.hasNext();) { |
| 1255 |
String key = (String) already.next(); |
| 1256 |
// property key is timestamp.key |
| 1257 |
if (key.startsWith(timestampString)) |
| 1258 |
already.remove(); |
| 1259 |
} |
| 1260 |
} else { |
| 1261 |
for (String key : keys) { |
| 1262 |
// property key format is timestamp.key |
| 1263 |
if (key != null) |
| 1264 |
properties.remove(timestampString + "." + key); //$NON-NLS-1$ |
| 1265 |
} |
| 1266 |
} |
| 1267 |
writeStateProperties(id, properties); |
| 1268 |
} catch (ProvisionException e) { |
| 1269 |
return e.getStatus(); |
| 1270 |
} finally { |
| 1271 |
internalUnlockProfile(internalProfile); |
| 1272 |
} |
| 1273 |
return Status.OK_STATUS; |
| 1274 |
} |
| 1275 |
} |