in src/main/java/org/apache/sling/discovery/oak/cluster/OakClusterViewService.java [445:493]
private String readOrDefineClusterId(ResourceResolver resourceResolver) throws PersistenceException {
//TODO: if Config gets a specific, public getDiscoveryResourcePath, this can be simplified:
final String clusterInstancesPath = config.getClusterInstancesPath();
final String discoveryResourcePath = clusterInstancesPath.substring(0,
clusterInstancesPath.lastIndexOf("/", clusterInstancesPath.length()-2));
final int MAX_RETRIES = 5;
for(int retryCnt=0; retryCnt<MAX_RETRIES; retryCnt++) {
Resource varDiscoveryOak = resourceResolver.getResource(discoveryResourcePath);
if (varDiscoveryOak == null) {
varDiscoveryOak = ResourceHelper.getOrCreateResource(resourceResolver, discoveryResourcePath);
}
if (varDiscoveryOak == null) {
logger.error("readOrDefinedClusterId: Could not create: "+discoveryResourcePath);
throw new RuntimeException("could not create " + discoveryResourcePath);
}
ModifiableValueMap props = varDiscoveryOak.adaptTo(ModifiableValueMap.class);
if (props == null) {
logger.error("readOrDefineClusterId: Could not adaptTo ModifiableValueMap: "+varDiscoveryOak);
throw new RuntimeException("could not adaptTo ModifiableValueMap: " + varDiscoveryOak);
}
Object clusterIdObj = props.get(PROPERTY_CLUSTER_ID);
String clusterId = (clusterIdObj == null) ? null : String.valueOf(clusterIdObj);
if (clusterId != null && clusterId.length() > 0) {
logger.trace("readOrDefineClusterId: read clusterId from repo as {}", clusterId);
return clusterId;
}
// must now define a new clusterId and store it under /var/discovery/oak
final String newClusterId = UUID.randomUUID().toString();
props.put(PROPERTY_CLUSTER_ID, newClusterId);
props.put(PROPERTY_CLUSTER_ID_DEFINED_BY, getSlingId());
props.put(PROPERTY_CLUSTER_ID_DEFINED_AT, Calendar.getInstance());
try {
logger.info("readOrDefineClusterId: storing new clusterId as " + newClusterId);
resourceResolver.commit();
return newClusterId;
} catch (PersistenceException e) {
logger.warn("readOrDefineClusterId: could not persist clusterId "
+ "(retrying in 1 sec max " + (MAX_RETRIES - retryCnt - 1) + " more times: " + e, e);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
logger.warn("readOrDefineClusterId: got interrupted: "+e1, e1);
}
logger.info("readOrDefineClusterId: retrying now.");
}
}
throw new RuntimeException("failed to write new clusterId (see log file earlier for more details)");
}