You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by st...@apache.org on 2015/10/21 17:50:37 UTC

svn commit: r1709867 [1/3] - in /sling/trunk/bundles/extensions/discovery/oak: ./ src/ src/main/ src/main/java/ src/main/java/org/ src/main/java/org/apache/ src/main/java/org/apache/sling/ src/main/java/org/apache/sling/discovery/ src/main/java/org/apa...

Author: stefanegli
Date: Wed Oct 21 15:50:37 2015
New Revision: 1709867

URL: http://svn.apache.org/viewvc?rev=1709867&view=rev
Log:
SLING-4603 : added discovery.oak to the project - this is based on discovery.base, which handles topology connectors and contains a few other base classes that were factored out of discovery.impl for exactly this reuse

Added:
    sling/trunk/bundles/extensions/discovery/oak/   (with props)
    sling/trunk/bundles/extensions/discovery/oak/pom.xml   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/
    sling/trunk/bundles/extensions/discovery/oak/src/main/
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/Config.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/OakDiscoveryService.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/TopologyWebConsolePlugin.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/cluster/
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/cluster/OakClusterViewService.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/pinger/
    sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/pinger/OakViewChecker.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/main/resources/
    sling/trunk/bundles/extensions/discovery/oak/src/main/resources/OSGI-INF/
    sling/trunk/bundles/extensions/discovery/oak/src/main/resources/OSGI-INF/metatype/
    sling/trunk/bundles/extensions/discovery/oak/src/main/resources/OSGI-INF/metatype/metatype.properties   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/test/
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/OakDiscoveryServiceTest.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/its/
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/its/OakClusterLoadTest.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/its/OakClusterTest.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/its/OakSingleInstanceTest.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/its/OakTopologyEventTest.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/its/setup/
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/its/setup/OakTestConfig.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/its/setup/OakVirtualInstanceBuilder.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/its/setup/SimulatedLease.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/test/java/org/apache/sling/discovery/oak/its/setup/SimulatedLeaseCollection.java   (with props)
    sling/trunk/bundles/extensions/discovery/oak/src/test/resources/
    sling/trunk/bundles/extensions/discovery/oak/src/test/resources/log4j.properties   (with props)

Propchange: sling/trunk/bundles/extensions/discovery/oak/
------------------------------------------------------------------------------
--- svn:ignore (added)
+++ svn:ignore Wed Oct 21 15:50:37 2015
@@ -0,0 +1,4 @@
+.classpath
+.project
+.settings
+target

Added: sling/trunk/bundles/extensions/discovery/oak/pom.xml
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/extensions/discovery/oak/pom.xml?rev=1709867&view=auto
==============================================================================
--- sling/trunk/bundles/extensions/discovery/oak/pom.xml (added)
+++ sling/trunk/bundles/extensions/discovery/oak/pom.xml Wed Oct 21 15:50:37 2015
@@ -0,0 +1,323 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing,
+  software distributed under the License is distributed on an
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  KIND, either express or implied.  See the License for the
+  specific language governing permissions and limitations
+  under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.apache.sling</groupId>
+        <artifactId>sling</artifactId>
+        <version>25</version>
+        <relativePath />
+    </parent>
+
+    <artifactId>org.apache.sling.discovery.oak</artifactId>
+    <packaging>bundle</packaging>
+    <version>1.0.0-SNAPSHOT</version>
+
+    <name>Apache Sling Oak-Based Discovery Service</name>
+    <description>Implementation of Apache Sling Discovery based on Jackrabbit Oak using its discovery-lite descriptor for in-cluster view detection and a TopologyView through HTTP POST heartbeats announcing sub-topologies to each other.</description>
+
+    <scm>
+        <connection>scm:svn:http://svn.apache.org/repos/asf/sling/trunk/bundles/extensions/discovery/oak</connection>
+        <developerConnection>scm:svn:https://svn.apache.org/repos/asf/sling/trunk/bundles/extensions/discovery/oak</developerConnection>
+        <url>http://svn.apache.org/viewvc/sling/trunk/bundles/extensions/discovery/oak</url>
+    </scm>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                 <artifactId>maven-surefire-plugin</artifactId>
+	  	 <configuration>
+       		 	<redirectTestOutputToFile>false</redirectTestOutputToFile>
+       		 	<argLine>-Xmx2048m</argLine>
+        	 </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <extensions>true</extensions>
+                <configuration>
+                  <instructions>
+		            <Embed-Dependency>
+		              commons-net;inline=org/apache/commons/net/util/SubnetUtils*
+		            </Embed-Dependency>
+		          </instructions>
+		        </configuration>
+            </plugin>
+        </plugins>
+    </build>
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.felix</groupId>
+            <artifactId>org.apache.felix.scr.annotations</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>biz.aQute</groupId>
+            <artifactId>bndlib</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+	        <version>1.6.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.osgi</groupId>
+            <artifactId>org.osgi.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.osgi</groupId>
+            <artifactId>org.osgi.compendium</artifactId>
+        </dependency>
+		<dependency>
+			<groupId>org.apache.sling</groupId>
+			<artifactId>org.apache.sling.jcr.api</artifactId>
+			<version>2.1.0</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>javax.jcr</groupId>
+			<artifactId>jcr</artifactId>
+			<version>2.0</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.jackrabbit</groupId>
+			<artifactId>jackrabbit-api</artifactId>
+			<version>2.2.4</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.sling</groupId>
+			<artifactId>org.apache.sling.commons.osgi</artifactId>
+			<version>2.1.0</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.sling</groupId>
+			<artifactId>org.apache.sling.settings</artifactId>
+			<version>1.2.2</version>
+            <scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.sling</groupId>
+			<artifactId>org.apache.sling.discovery.api</artifactId>
+			<version>1.0.0</version>
+            <scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.sling</groupId>
+			<artifactId>org.apache.sling.discovery.commons</artifactId>
+			<version>1.0.0-SNAPSHOT</version>
+            <scope>provided</scope>
+		</dependency>
+        <!-- besides including discovery.commons' normal jar above, 
+              for testing a few test helper classes are also reused.
+              in order to achieve that, also adding a test/test-jar dependency: --> 
+        <dependency>
+            <groupId>org.apache.sling</groupId>
+            <artifactId>org.apache.sling.discovery.commons</artifactId>
+            <version>1.0.0-SNAPSHOT</version>
+            <scope>test</scope>
+            <type>test-jar</type>
+        </dependency>
+		<dependency>
+			<groupId>org.apache.sling</groupId>
+			<artifactId>org.apache.sling.discovery.base</artifactId>
+			<version>1.0.0-SNAPSHOT</version>
+            <scope>provided</scope>
+		</dependency>
+        <!-- besides including discovery.base' normal jar above, 
+              for testing a few test helper classes are also reused.
+              in order to achieve that, also adding a test/test-jar dependency: --> 
+        <dependency>
+            <groupId>org.apache.sling</groupId>
+            <artifactId>org.apache.sling.discovery.base</artifactId>
+            <version>1.0.0-SNAPSHOT</version>
+            <scope>test</scope>
+            <type>test-jar</type>
+        </dependency>
+		<dependency>
+			<groupId>org.apache.sling</groupId>
+			<artifactId>org.apache.sling.api</artifactId>
+			<version>2.4.0</version>
+            <scope>provided</scope>
+		</dependency>
+        <dependency>
+        	<groupId>org.apache.sling</groupId>
+        	<artifactId>org.apache.sling.commons.scheduler</artifactId>
+        	<version>2.3.4</version>
+            <scope>provided</scope>
+        </dependency>
+		<dependency>
+			<groupId>org.apache.felix</groupId>
+			<artifactId>org.apache.felix.webconsole</artifactId>
+			<version>3.0.0</version>
+            <scope>provided</scope>
+		</dependency>
+	    <dependency>
+	      <groupId>org.eclipse.jetty</groupId>
+	      <artifactId>jetty-servlet</artifactId>
+	      <version>8.1.2.v20120308</version>
+	      <scope>test</scope>
+	    </dependency>
+		<dependency>
+			<groupId>javax.servlet</groupId>
+			<artifactId>servlet-api</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.httpcomponents</groupId>
+			<artifactId>httpclient-osgi</artifactId>
+			<version>4.3.5</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.sling</groupId>
+			<artifactId>org.apache.sling.commons.json</artifactId>
+			<version>2.0.6</version>
+            <scope>provided</scope>
+		</dependency>
+        <dependency>
+            <groupId>org.apache.sling</groupId>
+            <artifactId>org.apache.sling.launchpad.api</artifactId>
+		    <version>1.1.0</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+            <version>2.4</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>commons-net</groupId>
+            <artifactId>commons-net</artifactId>
+            <version>3.3</version>
+            <scope>provided</scope>
+        </dependency>
+      <!-- Testing -->
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>junit-addons</groupId>
+            <artifactId>junit-addons</artifactId>
+            <version>1.4</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jmock</groupId>
+            <artifactId>jmock-junit4</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-all</artifactId>
+            <version>1.9.5</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+        	<groupId>org.apache.sling</groupId>
+        	<artifactId>org.apache.sling.commons.testing</artifactId>
+        	<version>2.0.16</version>
+        	<scope>test</scope>
+            <exclusions>
+                <!-- slf4j simple implementation logs INFO + higher to stdout (we don't want that behaviour) -->
+                <exclusion>
+                    <groupId>org.slf4j</groupId>
+                    <artifactId>slf4j-simple</artifactId>
+                </exclusion>
+                <!--  also excluding jcl-over-slf4j as we need a newer vesion of this which is compatible with slf4j 1.6 -->
+                <exclusion>
+                    <groupId>org.slf4j</groupId>
+                    <artifactId>jcl-over-slf4j</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        
+        <!-- using log4j under slf4j to allow fine-grained logging config (see src/test/resources/log4j.properties) -->
+        <dependency>
+        	<groupId>org.slf4j</groupId>
+        	<artifactId>slf4j-log4j12</artifactId>
+        	<version>1.7.5</version>
+        	<scope>test</scope>
+        </dependency>
+        <dependency>
+        	<groupId>org.apache.sling</groupId>
+        	<artifactId>org.apache.sling.jcr.resource</artifactId>
+        	<version>2.3.8</version>
+        	<scope>test</scope>
+        </dependency>
+	    <dependency>
+			<groupId>log4j</groupId>
+			<artifactId>log4j</artifactId>
+			<version>1.2.13</version>
+			<scope>test</scope>
+	    </dependency>
+        <dependency>
+        	<groupId>org.apache.sling</groupId>
+        	<artifactId>org.apache.sling.commons.threads</artifactId>
+        	<version>3.1.0</version>
+        	<type>bundle</type>
+        	<scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.sling</groupId>
+            <artifactId>org.apache.sling.testing.tools</artifactId>
+            <version>1.0.2</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+          <groupId>org.apache.sling</groupId>
+          <artifactId>org.apache.sling.testing.sling-mock</artifactId>
+          <version>1.2.0</version>
+        </dependency>
+        <dependency>
+        	<groupId>org.apache.jackrabbit</groupId>
+        	<artifactId>jackrabbit-jcr-commons</artifactId>
+        	<version>2.11.0</version>
+        	<type>bundle</type>
+        	<scope>test</scope>
+        </dependency>
+        <dependency>
+        	<groupId>org.apache.jackrabbit</groupId>
+        	<artifactId>jackrabbit-api</artifactId>
+        	<version>2.11.0</version>
+        	<type>bundle</type>
+        	<scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.jackrabbit</groupId>
+            <artifactId>oak-core</artifactId>
+            <version>1.3.7</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.jackrabbit</groupId>
+            <artifactId>oak-jcr</artifactId>
+            <version>1.3.7</version>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+</project>

Propchange: sling/trunk/bundles/extensions/discovery/oak/pom.xml
------------------------------------------------------------------------------
    svn:eol-style = native

Added: sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/Config.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/Config.java?rev=1709867&view=auto
==============================================================================
--- sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/Config.java (added)
+++ sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/Config.java Wed Oct 21 15:50:37 2015
@@ -0,0 +1,470 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.discovery.oak;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Service;
+import org.apache.sling.commons.osgi.PropertiesUtil;
+import org.apache.sling.discovery.base.connectors.BaseConfig;
+import org.apache.sling.discovery.commons.providers.spi.base.DiscoveryLiteConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Configuration object used as a central config point for the discovery service
+ * implementation
+ * <p>
+ * The properties are described below under.
+ */
+@Component(metatype = true, label="%config.name", description="%config.description")
+@Service(value = { Config.class, BaseConfig.class, DiscoveryLiteConfig.class })
+public class Config implements BaseConfig, DiscoveryLiteConfig {
+
+    private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+    /** resource used to keep instance information such as last heartbeat, properties, incoming announcements **/
+    private static final String CLUSTERINSTANCES_RESOURCE = "clusterInstances";
+
+    /** resource used to store the sync tokens as part of a topology change **/
+    private static final String SYNC_TOKEN_RESOURCE = "syncTokens";
+
+    /** resource used to store the clusterNodeIds to slingIds map **/
+    private static final String ID_MAP_RESOURCE = "idMap";
+
+    /** Configure the timeout (in seconds) after which an instance is considered dead/crashed. */
+    public static final long DEFAULT_TOPOLOGY_CONNECTOR_TIMEOUT = 120;
+    @Property(longValue=DEFAULT_TOPOLOGY_CONNECTOR_TIMEOUT)
+    public static final String TOPOLOGY_CONNECTOR_TIMEOUT_KEY = "connectorPingTimeout";
+    protected long connectorPingTimeout = DEFAULT_TOPOLOGY_CONNECTOR_TIMEOUT;
+
+    /** Configure the interval (in seconds) according to which the heartbeats are exchanged in the topology. */
+    public static final long DEFAULT_TOPOLOGY_CONNECTOR_INTERVAL = 30;
+    @Property(longValue=DEFAULT_TOPOLOGY_CONNECTOR_INTERVAL)
+    public static final String TOPOLOGY_CONNECTOR_INTERVAL_KEY = "connectorPingInterval";
+    protected long connectorPingInterval = DEFAULT_TOPOLOGY_CONNECTOR_INTERVAL;
+    
+    /** Configure the interval (in seconds) according to which the heartbeats are exchanged in the topology. */
+    public static final long DEFAULT_DISCOVERY_LITE_CHECK_INTERVAL = 2;
+    @Property(longValue=DEFAULT_DISCOVERY_LITE_CHECK_INTERVAL)
+    public static final String DISCOVERY_LITE_CHECK_INTERVAL_KEY = "discoveryLiteCheckInterval";
+    protected long discoveryLiteCheckInterval = DEFAULT_DISCOVERY_LITE_CHECK_INTERVAL;
+    
+    /** Configure the time (in seconds) which must be passed at minimum between sending TOPOLOGY_CHANGING/_CHANGED (avoid flooding). */
+    public static final int DEFAULT_MIN_EVENT_DELAY = 3;
+    @Property(intValue=DEFAULT_MIN_EVENT_DELAY)
+    public static final String MIN_EVENT_DELAY_KEY = "minEventDelay";
+    protected int minEventDelay = DEFAULT_MIN_EVENT_DELAY;
+
+    /** Configure the socket connect timeout for topology connectors. */
+    public static final int DEFAULT_SOCKET_CONNECT_TIMEOUT = 10;
+    @Property(intValue=DEFAULT_SOCKET_CONNECT_TIMEOUT)
+    public static final String SOCKET_CONNECT_TIMEOUT_KEY = "socketConnectTimeout";
+    private int socketConnectTimeout = DEFAULT_SOCKET_CONNECT_TIMEOUT;
+
+    /** Configure the socket read timeout (SO_TIMEOUT) for topology connectors. */
+    public static final int DEFAULT_SO_TIMEOUT = 10;
+    @Property(intValue=DEFAULT_SO_TIMEOUT)
+    public static final String SO_TIMEOUT_KEY = "soTimeout";
+    private int soTimeout = DEFAULT_SO_TIMEOUT;
+
+    /** URLs where to join a topology, eg http://localhost:4502/libs/sling/topology/connector */
+    @Property(cardinality=1024)
+    public static final String TOPOLOGY_CONNECTOR_URLS_KEY = "topologyConnectorUrls";
+    private URL[] topologyConnectorUrls = {null};
+
+    /** list of ips and/or hostnames which are allowed to connect to /libs/sling/topology/connector */
+    private static final String[] DEFAULT_TOPOLOGY_CONNECTOR_WHITELIST = {"localhost","127.0.0.1"};
+    @Property(value={"localhost","127.0.0.1"})
+    public static final String TOPOLOGY_CONNECTOR_WHITELIST_KEY = "topologyConnectorWhitelist";
+    protected String[] topologyConnectorWhitelist = DEFAULT_TOPOLOGY_CONNECTOR_WHITELIST;
+
+    /** Path of resource where to keep discovery information, e.g /var/discovery/oak/ */
+    private static final String DEFAULT_DISCOVERY_RESOURCE_PATH = "/var/discovery/oak/";
+    @Property(value=DEFAULT_DISCOVERY_RESOURCE_PATH, propertyPrivate=true)
+    public static final String DISCOVERY_RESOURCE_PATH_KEY = "discoveryResourcePath";
+    protected String discoveryResourcePath = DEFAULT_DISCOVERY_RESOURCE_PATH;
+
+    /**
+     * If set to true, local-loops of topology connectors are automatically stopped when detected so.
+     */
+    @Property(boolValue=false)
+    private static final String AUTO_STOP_LOCAL_LOOP_ENABLED = "autoStopLocalLoopEnabled";
+
+    /**
+     * If set to true, request body will be gzipped - only works if counter-part accepts gzip-requests!
+     */
+    @Property(boolValue=false)
+    private static final String GZIP_CONNECTOR_REQUESTS_ENABLED = "gzipConnectorRequestsEnabled";
+
+    /**
+     * If set to true, hmac is enabled and the white list is disabled.
+     */
+    @Property(boolValue=false)
+    private static final String HMAC_ENABLED = "hmacEnabled";
+
+    /**
+     * If set to true, and the whitelist is disabled, messages will be encrypted.
+     */
+    @Property(boolValue=false)
+    private static final String ENCRYPTION_ENABLED = "enableEncryption";
+
+    /**
+     * The value fo the shared key, shared amongst all instances in the same cluster.
+     */
+    @Property
+    private static final String SHARED_KEY = "sharedKey";
+
+    /**
+     * The default lifetime of a HMAC shared key in ms. (4h)
+     */
+    private static final long DEFAULT_SHARED_KEY_INTERVAL = 3600*1000*4;
+
+    @Property(longValue=DEFAULT_SHARED_KEY_INTERVAL)
+    private static final String SHARED_KEY_INTERVAL = "hmacSharedKeyTTL";
+    
+    /**
+     * The property for defining the backoff factor for standby (loop) connectors
+     */
+    @Property
+    private static final String BACKOFF_STANDBY_FACTOR = "backoffStandbyFactor";
+    private static final int DEFAULT_BACKOFF_STANDBY_FACTOR = 5;
+    
+    /**
+     * The property for defining the maximum backoff factor for stable connectors
+     */
+    @Property
+    private static final String BACKOFF_STABLE_FACTOR = "backoffStableFactor";
+    private static final int DEFAULT_BACKOFF_STABLE_FACTOR = 5;
+
+    /** True when auto-stop of a local-loop is enabled. Default is false. **/
+    private boolean autoStopLocalLoopEnabled;
+    
+    /**
+     * True when the hmac is enabled and signing is disabled.
+     */
+    private boolean hmacEnabled;
+
+    /**
+     * the shared key.
+     */
+    private String sharedKey;
+
+    /**
+     * The key interval.
+     */
+    private long keyInterval;
+
+    /**
+     * true when encryption is enabled.
+     */
+    private boolean encryptionEnabled;
+    
+    /**
+     * true when topology connector requests should be gzipped
+     */
+    private boolean gzipConnectorRequestsEnabled;
+
+    /** the backoff factor to be used for standby (loop) connectors **/
+    private int backoffStandbyFactor = DEFAULT_BACKOFF_STANDBY_FACTOR;
+    
+    /** the maximum backoff factor to be used for stable connectors **/
+    private int backoffStableFactor = DEFAULT_BACKOFF_STABLE_FACTOR;
+    
+    @Activate
+    protected void activate(final Map<String, Object> properties) {
+		logger.debug("activate: config activated.");
+        configure(properties);
+    }
+
+    protected void configure(final Map<String, Object> properties) {
+        this.connectorPingTimeout = PropertiesUtil.toLong(
+                properties.get(TOPOLOGY_CONNECTOR_TIMEOUT_KEY),
+                DEFAULT_TOPOLOGY_CONNECTOR_TIMEOUT);
+        logger.debug("configure: connectorPingTimeout='{}'", 
+                this.connectorPingTimeout);
+
+        this.connectorPingInterval = PropertiesUtil.toLong(
+                properties.get(TOPOLOGY_CONNECTOR_INTERVAL_KEY),
+                DEFAULT_TOPOLOGY_CONNECTOR_INTERVAL);
+        logger.debug("configure: connectorPingInterval='{}'",
+                this.connectorPingInterval);
+        
+        this.discoveryLiteCheckInterval = PropertiesUtil.toLong(
+                properties.get(DISCOVERY_LITE_CHECK_INTERVAL_KEY),
+                DEFAULT_DISCOVERY_LITE_CHECK_INTERVAL);
+        logger.debug("configure: discoveryLiteCheckInterval='{}'",
+                this.discoveryLiteCheckInterval);
+                
+
+        this.minEventDelay = PropertiesUtil.toInteger(
+                properties.get(MIN_EVENT_DELAY_KEY),
+                DEFAULT_MIN_EVENT_DELAY);
+        logger.debug("configure: minEventDelay='{}'",
+                this.minEventDelay);
+        
+        this.socketConnectTimeout = PropertiesUtil.toInteger(
+                properties.get(SOCKET_CONNECT_TIMEOUT_KEY),
+                DEFAULT_SOCKET_CONNECT_TIMEOUT);
+        logger.debug("configure: socketConnectTimeout='{}'",
+                this.socketConnectTimeout);
+        
+        this.soTimeout = PropertiesUtil.toInteger(
+                properties.get(SO_TIMEOUT_KEY),
+                DEFAULT_SO_TIMEOUT);
+        logger.debug("configure: soTimeout='{}'",
+                this.soTimeout);
+        
+        
+        String[] topologyConnectorUrlsStr = PropertiesUtil.toStringArray(
+                properties.get(TOPOLOGY_CONNECTOR_URLS_KEY), null);
+        if (topologyConnectorUrlsStr!=null && topologyConnectorUrlsStr.length > 0) {
+            List<URL> urls = new LinkedList<URL>();
+            for (int i = 0; i < topologyConnectorUrlsStr.length; i++) {
+                String anUrlStr = topologyConnectorUrlsStr[i];
+                try {
+                	if (anUrlStr!=null && anUrlStr.length()>0) {
+	                    URL url = new URL(anUrlStr);
+	                    logger.debug("configure: a topologyConnectorbUrl='{}'",
+	                            url);
+	                    urls.add(url);
+                	}
+                } catch (MalformedURLException e) {
+                    logger.error("configure: could not set a topologyConnectorUrl: " + e,
+                            e);
+                }
+            }
+            if (urls.size()>0) {
+                this.topologyConnectorUrls = urls.toArray(new URL[urls.size()]);
+                logger.debug("configure: number of topologyConnectorUrls='{}''",
+                        urls.size());
+            } else {
+                this.topologyConnectorUrls = null;
+                logger.debug("configure: no (valid) topologyConnectorUrls configured");
+            }
+        } else {
+            this.topologyConnectorUrls = null;
+            logger.debug("configure: no (valid) topologyConnectorUrls configured");
+        }
+        this.topologyConnectorWhitelist = PropertiesUtil.toStringArray(
+                properties.get(TOPOLOGY_CONNECTOR_WHITELIST_KEY),
+                DEFAULT_TOPOLOGY_CONNECTOR_WHITELIST);
+        logger.debug("configure: topologyConnectorWhitelist='{}'",
+                this.topologyConnectorWhitelist);
+
+        this.discoveryResourcePath = PropertiesUtil.toString(
+                properties.get(DISCOVERY_RESOURCE_PATH_KEY),
+                "");
+        while(this.discoveryResourcePath.endsWith("/")) {
+            this.discoveryResourcePath = this.discoveryResourcePath.substring(0,
+                    this.discoveryResourcePath.length()-1);
+        }
+        this.discoveryResourcePath = this.discoveryResourcePath + "/";
+        if (this.discoveryResourcePath==null || this.discoveryResourcePath.length()<=1) {
+            // if the path is empty, or /, then use the default
+            this.discoveryResourcePath = DEFAULT_DISCOVERY_RESOURCE_PATH;
+        }
+        logger.debug("configure: discoveryResourcePath='{}'",
+                this.discoveryResourcePath);
+
+        autoStopLocalLoopEnabled = PropertiesUtil.toBoolean(properties.get(AUTO_STOP_LOCAL_LOOP_ENABLED), false);
+        gzipConnectorRequestsEnabled = PropertiesUtil.toBoolean(properties.get(GZIP_CONNECTOR_REQUESTS_ENABLED), false);
+        
+        hmacEnabled = PropertiesUtil.toBoolean(properties.get(HMAC_ENABLED), true);
+        encryptionEnabled = PropertiesUtil.toBoolean(properties.get(ENCRYPTION_ENABLED), false);
+        sharedKey = PropertiesUtil.toString(properties.get(SHARED_KEY), null);
+        keyInterval = PropertiesUtil.toLong(SHARED_KEY_INTERVAL, DEFAULT_SHARED_KEY_INTERVAL);
+        
+        backoffStandbyFactor = PropertiesUtil.toInteger(properties.get(BACKOFF_STANDBY_FACTOR), 
+                DEFAULT_BACKOFF_STANDBY_FACTOR);
+        backoffStableFactor = PropertiesUtil.toInteger(properties.get(BACKOFF_STABLE_FACTOR), 
+                DEFAULT_BACKOFF_STABLE_FACTOR);
+    }
+
+    /**
+     * Returns the socket connect() timeout used by the topology connector, 0 disables the timeout
+     * @return the socket connect() timeout used by the topology connector, 0 disables the timeout
+     */
+    public int getSocketConnectTimeout() {
+        return socketConnectTimeout;
+    }
+
+    /**
+     * Returns the socket read timeout (SO_TIMEOUT) used by the topology connector, 0 disables the timeout
+     * @return the socket read timeout (SO_TIMEOUT) used by the topology connector, 0 disables the timeout
+     */
+    public int getSoTimeout() {
+        return soTimeout;
+    }
+    
+    /**
+     * Returns the minimum time (in seconds) between sending TOPOLOGY_CHANGING/_CHANGED events - to avoid flooding
+     * @return the minimum time (in seconds) between sending TOPOLOGY_CHANGING/_CHANGED events - to avoid flooding
+     */
+    public int getMinEventDelay() {
+        return minEventDelay;
+    }
+
+    /**
+     * Returns the URLs to which to open a topology connector - or null/empty if no topology connector
+     * is configured (default is null)
+     * @return the URLs to which to open a topology connector - or null/empty if no topology connector
+     * is configured
+     */
+    public URL[] getTopologyConnectorURLs() {
+        return topologyConnectorUrls;
+    }
+
+    /**
+     * Returns a comma separated list of hostnames and/or ip addresses which are allowed as
+     * remote hosts to open connections to the topology connector servlet
+     * @return a comma separated list of hostnames and/or ip addresses which are allowed as
+     * remote hosts to open connections to the topology connector servlet
+     */
+    public String[] getTopologyConnectorWhitelist() {
+        return topologyConnectorWhitelist;
+    }
+    
+    protected String getDiscoveryResourcePath() {
+        return discoveryResourcePath;
+    }
+
+    /**
+     * Returns the resource path where cluster instance informations are stored.
+     * @return the resource path where cluster instance informations are stored
+     */
+    public String getClusterInstancesPath() {
+        return getDiscoveryResourcePath() + CLUSTERINSTANCES_RESOURCE;
+    }
+
+    @Override
+    public String getSyncTokenPath() {
+        return getDiscoveryResourcePath() + SYNC_TOKEN_RESOURCE;
+    }
+
+    @Override
+    public String getIdMapPath() {
+        return getDiscoveryResourcePath() + ID_MAP_RESOURCE;
+    }
+
+    /**
+     * @return true if hmac is enabled.
+     */
+    public boolean isHmacEnabled() {
+        return hmacEnabled;
+    }
+
+    /**
+     * @return the shared key
+     */
+    public String getSharedKey() {
+        return sharedKey;
+    }
+
+    /**
+     * @return the interval of the shared key for hmac.
+     */
+    public long getKeyInterval() {
+        return keyInterval;
+    }
+
+    /**
+     * @return true if encryption is enabled.
+     */
+    public boolean isEncryptionEnabled() {
+        return encryptionEnabled;
+    }
+    
+    /**
+     * @return true if requests on the topology connector should be gzipped
+     * (which only works if the server accepts that.. ie discovery.impl 1.0.4+)
+     */
+    public boolean isGzipConnectorRequestsEnabled() {
+        return gzipConnectorRequestsEnabled;
+    }
+    
+    /**
+     * @return true if the auto-stopping of local-loop topology connectors is enabled.
+     */
+    public boolean isAutoStopLocalLoopEnabled() {
+        return autoStopLocalLoopEnabled;
+    }
+
+    /**
+     * Returns the backoff factor to be used for standby (loop) connectors
+     * @return the backoff factor to be used for standby (loop) connectors
+     */
+    public int getBackoffStandbyFactor() {
+        return backoffStandbyFactor;
+    }
+
+    /**
+     * Returns the (maximum) backoff factor to be used for stable connectors
+     * @return the (maximum) backoff factor to be used for stable connectors
+     */
+    public int getBackoffStableFactor() {
+        return backoffStableFactor;
+    }
+
+    /**
+     * Returns the backoff interval for standby (loop) connectors in seconds
+     * @return the backoff interval for standby (loop) connectors in seconds
+     */
+    public long getBackoffStandbyInterval() {
+        final int factor = getBackoffStandbyFactor();
+        if (factor<=1) {
+            return -1;
+        } else {
+            return factor * getConnectorPingInterval();
+        }
+    }
+
+    @Override
+    public long getConnectorPingInterval() {
+        return connectorPingInterval;
+    }
+    
+    @Override
+    public long getConnectorPingTimeout() {
+        return connectorPingTimeout;
+    }
+    
+    public long getDiscoveryLiteCheckInterval() {
+        return discoveryLiteCheckInterval;
+    }
+    
+    @Override
+    public long getBgTimeoutMillis() {
+        // TODO: currently hard coded
+        return -1;
+    }
+
+    @Override
+    public long getBgIntervalMillis() {
+        // TODO: currently hard coded
+        return 1000;
+    }
+}

Propchange: sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/Config.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/OakDiscoveryService.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/OakDiscoveryService.java?rev=1709867&view=auto
==============================================================================
--- sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/OakDiscoveryService.java (added)
+++ sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/OakDiscoveryService.java Wed Oct 21 15:50:37 2015
@@ -0,0 +1,642 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.discovery.oak;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.apache.felix.scr.annotations.ReferencePolicy;
+import org.apache.felix.scr.annotations.Service;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.ModifiableValueMap;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.commons.scheduler.Scheduler;
+import org.apache.sling.discovery.DiscoveryService;
+import org.apache.sling.discovery.InstanceDescription;
+import org.apache.sling.discovery.PropertyProvider;
+import org.apache.sling.discovery.TopologyEventListener;
+import org.apache.sling.discovery.base.commons.BaseDiscoveryService;
+import org.apache.sling.discovery.base.commons.ClusterViewService;
+import org.apache.sling.discovery.base.commons.DefaultTopologyView;
+import org.apache.sling.discovery.base.connectors.announcement.AnnouncementRegistry;
+import org.apache.sling.discovery.base.connectors.ping.ConnectorRegistry;
+import org.apache.sling.discovery.commons.providers.BaseTopologyView;
+import org.apache.sling.discovery.commons.providers.DefaultClusterView;
+import org.apache.sling.discovery.commons.providers.DefaultInstanceDescription;
+import org.apache.sling.discovery.commons.providers.ViewStateManager;
+import org.apache.sling.discovery.commons.providers.base.ViewStateManagerFactory;
+import org.apache.sling.discovery.commons.providers.spi.base.IdMapService;
+import org.apache.sling.discovery.commons.providers.spi.base.OakSyncTokenConsistencyService;
+import org.apache.sling.discovery.commons.providers.util.PropertyNameHelper;
+import org.apache.sling.discovery.commons.providers.util.ResourceHelper;
+import org.apache.sling.discovery.oak.pinger.OakViewChecker;
+import org.apache.sling.settings.SlingSettingsService;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+import org.osgi.framework.ServiceRegistration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This implementation of the cross-cluster service uses the view manager
+ * implementation for detecting changes in a cluster and only supports one
+ * cluster (of which this instance is part of).
+ */
+@Component(immediate = true)
+@Service(value = { DiscoveryService.class, OakDiscoveryService.class })
+public class OakDiscoveryService extends BaseDiscoveryService {
+
+    private final static Logger logger = LoggerFactory.getLogger(OakDiscoveryService.class);
+
+    @Reference
+    private SlingSettingsService settingsService;
+
+    @Reference(cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC, referenceInterface = TopologyEventListener.class)
+    private TopologyEventListener[] eventListeners = new TopologyEventListener[0];
+    
+    /**
+     * All property providers.
+     */
+    @Reference(cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC, referenceInterface = PropertyProvider.class, updated = "updatedPropertyProvider")
+    private List<ProviderInfo> providerInfos = new ArrayList<ProviderInfo>();
+
+    /** lock object used for synching bind/unbind and topology event sending **/
+    private final Object lock = new Object();
+
+    /**
+     * whether or not this service is activated - necessary to avoid sending
+     * events to discovery awares before activate is done
+     **/
+    private boolean activated = false;
+
+    @Reference
+    private ResourceResolverFactory resourceResolverFactory;
+
+    @Reference
+    private Scheduler scheduler;
+
+    @Reference
+    private OakViewChecker oakViewChecker;
+
+    @Reference
+    private AnnouncementRegistry announcementRegistry;
+
+    @Reference
+    private ConnectorRegistry connectorRegistry;
+
+    @Reference
+    private ClusterViewService clusterViewService;
+
+    @Reference
+    private Config config;
+
+    @Reference
+    private IdMapService idMapService;
+    
+    @Reference
+    private OakSyncTokenConsistencyService consistencyService;
+
+    /** the slingId of the local instance **/
+    private String slingId;
+
+    private ServiceRegistration mbeanRegistration;
+
+    private ViewStateManager viewStateManager;
+
+    private final ReentrantLock viewStateManagerLock = new ReentrantLock(); 
+    
+    private final List<TopologyEventListener> pendingListeners = new LinkedList<TopologyEventListener>();
+    
+    public static OakDiscoveryService testConstructor(SlingSettingsService settingsService,
+            AnnouncementRegistry announcementRegistry,
+            ConnectorRegistry connectorRegistry,
+            ClusterViewService clusterViewService,
+            Config config,
+            OakViewChecker connectorPinger,
+            Scheduler scheduler,
+            IdMapService idMapService,
+            OakSyncTokenConsistencyService consistencyService,
+            ResourceResolverFactory factory) {
+        OakDiscoveryService discoService = new OakDiscoveryService();
+        discoService.settingsService = settingsService;
+        discoService.announcementRegistry = announcementRegistry;
+        discoService.connectorRegistry = connectorRegistry;
+        discoService.clusterViewService = clusterViewService;
+        discoService.config = config;
+        discoService.oakViewChecker = connectorPinger;
+        discoService.scheduler = scheduler;
+        discoService.idMapService = idMapService;
+        discoService.consistencyService = consistencyService;
+        discoService.resourceResolverFactory = factory;
+        return discoService;
+    }
+
+    protected void handleIsolatedFromTopology() {
+        if (oakViewChecker!=null) {
+            // SLING-5030 part 2: when we detect being isolated we should
+            // step at the end of the leader-election queue and 
+            // that can be achieved by resetting the leaderElectionId
+            // (which will in turn take effect on the next round of
+            // voting, or also double-checked when the local instance votes)
+            //
+            //TODO:
+            // Note that when the local instance doesn't notice
+            // an 'ISOLATED_FROM_TOPOLOGY' case, then the leaderElectionId
+            // will not be reset. Which means that it then could potentially
+            // regain leadership.
+            if (oakViewChecker.resetLeaderElectionId()) {
+                logger.info("getTopology: reset leaderElectionId to force this instance to the end of the instance order (thus incl not to remain leader)");
+            }
+        }
+    }
+    
+    /**
+     * Activate this service
+     */
+    @Activate
+    protected void activate(final BundleContext bundleContext) {
+        logger.debug("OakDiscoveryService activating...");
+
+        if (settingsService == null) {
+            throw new IllegalStateException("settingsService not found");
+        }
+        if (oakViewChecker == null) {
+            throw new IllegalStateException("heartbeatHandler not found");
+        }
+
+        slingId = settingsService.getSlingId();
+
+        //TODO: this should fail as bind can now run into viewStateManager==null
+        viewStateManager = ViewStateManagerFactory.newViewStateManager(viewStateManagerLock, consistencyService);
+
+        if (config.getMinEventDelay()>0) {
+            viewStateManager.installMinEventDelayHandler(this, scheduler, config.getMinEventDelay());
+        }
+
+        final String isolatedClusterId = UUID.randomUUID().toString();
+        {
+            // create a pre-voting/isolated topologyView which would be used
+            // until the first voting has finished.
+            // this way for the single-instance case the clusterId can
+            // remain the same between a getTopology() that is invoked before
+            // the first TOPOLOGY_INIT and afterwards
+            DefaultClusterView isolatedCluster = new DefaultClusterView(isolatedClusterId);
+            Map<String, String> emptyProperties = new HashMap<String, String>();
+            DefaultInstanceDescription isolatedInstance = 
+                    new DefaultInstanceDescription(isolatedCluster, true, true, slingId, emptyProperties);
+            Collection<InstanceDescription> col = new ArrayList<InstanceDescription>();
+            col.add(isolatedInstance);
+            final DefaultTopologyView topology = new DefaultTopologyView();
+            topology.addInstances(col);
+            topology.setNotCurrent();
+            setOldView(topology);
+        }
+        setOldView((DefaultTopologyView) getTopology());
+        getOldView().setNotCurrent();
+
+        // make sure the first heartbeat is issued as soon as possible - which
+        // is right after this service starts. since the two (discoveryservice
+        // and heartbeatHandler need to know each other, the discoveryservice
+        // is passed on to the heartbeatHandler in this initialize call).
+        oakViewChecker.initialize(this);
+
+        viewStateManagerLock.lock();
+        try{
+            viewStateManager.handleActivated();
+
+            doUpdateProperties();
+
+            DefaultTopologyView newView = (DefaultTopologyView) getTopology();
+            if (newView.isCurrent()) {
+                viewStateManager.handleNewView(newView);
+            } else {
+                // SLING-3750: just issue a log.info about the delaying
+                logger.info("activate: this instance is in isolated mode and must yet finish voting before it can send out TOPOLOGY_INIT.");
+            }
+            activated = true;
+            setOldView(newView);
+            
+            // in case bind got called before activate we now have pending listeners,
+            // bind them to the viewstatemanager too
+            for (TopologyEventListener listener : pendingListeners) {
+                viewStateManager.bind(listener);
+            }
+            pendingListeners.clear();
+        } finally {
+            if (viewStateManagerLock!=null) {
+                viewStateManagerLock.unlock();
+            }
+        }
+
+        URL[] topologyConnectorURLs = config.getTopologyConnectorURLs();
+        if (topologyConnectorURLs != null) {
+            for (int i = 0; i < topologyConnectorURLs.length; i++) {
+                final URL aURL = topologyConnectorURLs[i];
+                if (aURL!=null) {
+                	try{
+                		logger.info("activate: registering outgoing topology connector to "+aURL);
+                		connectorRegistry.registerOutgoingConnector(clusterViewService, aURL);
+                	} catch (final Exception e) {
+                		logger.info("activate: could not register url: "+aURL+" due to: "+e, e);
+                	}
+                }
+            }
+        }
+        
+        logger.debug("OakDiscoveryService activated.");
+    }
+
+    /**
+     * Deactivate this service
+     */
+    @Deactivate
+    protected void deactivate() {
+        logger.debug("OakDiscoveryService deactivated.");
+        viewStateManagerLock.lock();
+        try{
+            viewStateManager.handleDeactivated();
+            
+            activated = false;
+        } finally {
+            if (viewStateManagerLock!=null) {
+                viewStateManagerLock.unlock();
+            }
+        }
+        try{
+            if ( this.mbeanRegistration != null ) {
+                this.mbeanRegistration.unregister();
+                this.mbeanRegistration = null;
+            }
+        } catch(Exception e) {
+            logger.error("deactivate: Error on unregister: "+e, e);
+        }
+    }
+
+    /**
+     * bind a topology event listener
+     */
+    protected void bindTopologyEventListener(final TopologyEventListener eventListener) {
+        viewStateManagerLock.lock();
+        try{
+            if (!activated) {
+                pendingListeners.add(eventListener);
+            } else {
+                viewStateManager.bind(eventListener);
+            }
+        } finally {
+            if (viewStateManagerLock!=null) {
+                viewStateManagerLock.unlock();
+            }
+        }
+    }
+
+    /**
+     * Unbind a topology event listener
+     */
+    protected void unbindTopologyEventListener(final TopologyEventListener eventListener) {
+        viewStateManagerLock.lock();
+        try{
+            if (!activated) {
+                pendingListeners.remove(eventListener);
+            } else {
+                viewStateManager.unbind(eventListener);
+            }
+        } finally {
+            if (viewStateManagerLock!=null) {
+                viewStateManagerLock.unlock();
+            }
+        }
+    }
+
+    /**
+     * Bind a new property provider.
+     */
+    protected void bindPropertyProvider(final PropertyProvider propertyProvider,
+                                        final Map<String, Object> props) {
+        logger.debug("bindPropertyProvider: Binding PropertyProvider {}",
+                propertyProvider);
+
+        synchronized (lock) {
+            this.bindPropertyProviderInteral(propertyProvider, props);
+        }
+    }
+
+    /**
+     * Bind a new property provider.
+     */
+    private void bindPropertyProviderInteral(final PropertyProvider propertyProvider,
+            final Map<String, Object> props) {
+        final ProviderInfo info = new ProviderInfo(propertyProvider, props);
+        this.providerInfos.add(info);
+        Collections.sort(this.providerInfos);
+        this.doUpdateProperties();
+        handlePotentialTopologyChange();
+    }
+
+    /**
+     * Update a property provider.
+     */
+    protected void updatedPropertyProvider(final PropertyProvider propertyProvider,
+                                           final Map<String, Object> props) {
+        logger.debug("bindPropertyProvider: Updating PropertyProvider {}",
+                propertyProvider);
+
+        synchronized (lock) {
+           this.unbindPropertyProviderInternal(propertyProvider, props, false);
+           this.bindPropertyProviderInteral(propertyProvider, props);
+        }
+    }
+
+    /**
+     * Unbind a property provider
+     */
+    protected void unbindPropertyProvider(final PropertyProvider propertyProvider,
+                                          final Map<String, Object> props) {
+        logger.debug("unbindPropertyProvider: Releasing PropertyProvider {}",
+                propertyProvider);
+        synchronized (lock) {
+            this.unbindPropertyProviderInternal(propertyProvider, props, true);
+        }
+    }
+
+    /**
+     * Unbind a property provider
+     */
+    private void unbindPropertyProviderInternal(
+            final PropertyProvider propertyProvider,
+            final Map<String, Object> props, final boolean update) {
+
+        final ProviderInfo info = new ProviderInfo(propertyProvider, props);
+        if ( this.providerInfos.remove(info) && update ) {
+            this.doUpdateProperties();
+            this.handlePotentialTopologyChange();
+        }
+    }
+
+    /**
+     * Update the properties by inquiring the PropertyProvider's current values.
+     * <p>
+     * This method is invoked regularly by the heartbeatHandler.
+     * The properties are stored in the repository under Config.getClusterInstancesPath()
+     * and announced in the topology.
+     * <p>
+     * @see Config#getClusterInstancesPath()
+     */
+    private void doUpdateProperties() {
+        if (resourceResolverFactory == null) {
+            // cannot update the properties then..
+            logger.debug("doUpdateProperties: too early to update the properties. resourceResolverFactory not yet set.");
+            return;
+        } else {
+            logger.debug("doUpdateProperties: updating properties now..");
+        }
+
+        final Map<String, String> newProps = new HashMap<String, String>();
+        for (final ProviderInfo info : this.providerInfos) {
+            info.refreshProperties();
+            newProps.putAll(info.properties);
+        }
+
+        ResourceResolver resourceResolver = null;
+        try {
+            resourceResolver = resourceResolverFactory
+                    .getAdministrativeResourceResolver(null);
+
+            Resource myInstance = ResourceHelper
+                    .getOrCreateResource(
+                            resourceResolver,
+                            config.getClusterInstancesPath()
+                                    + "/" + slingId + "/properties");
+            // SLING-2879 - revert/refresh resourceResolver here to work
+            // around a potential issue with jackrabbit in a clustered environment
+            resourceResolver.revert();
+            resourceResolver.refresh();
+
+            final ModifiableValueMap myInstanceMap = myInstance.adaptTo(ModifiableValueMap.class);
+            final Set<String> keys = new HashSet<String>(myInstanceMap.keySet());
+            for(final String key : keys) {
+                if (newProps.containsKey(key)) {
+                    // perfect
+                    continue;
+                } else if (key.indexOf(":")!=-1) {
+                    // ignore
+                    continue;
+                } else {
+                    // remove
+                	myInstanceMap.remove(key);
+                }
+            }
+
+            boolean anyChanges = false;
+            for(final Entry<String, String> entry : newProps.entrySet()) {
+            	Object existingValue = myInstanceMap.get(entry.getKey());
+            	if (entry.getValue().equals(existingValue)) {
+            	    // SLING-3389: dont rewrite the properties if nothing changed!
+                    if (logger.isDebugEnabled()) {
+                        logger.debug("doUpdateProperties: unchanged: {}={}", entry.getKey(), entry.getValue());
+                    }
+            	    continue;
+            	}
+            	if (logger.isDebugEnabled()) {
+            	    logger.debug("doUpdateProperties: changed: {}={}", entry.getKey(), entry.getValue());
+            	}
+            	anyChanges = true;
+                myInstanceMap.put(entry.getKey(), entry.getValue());
+            }
+
+            if (anyChanges) {
+                resourceResolver.commit();
+            }
+        } catch (LoginException e) {
+            logger.error(
+                    "handleEvent: could not log in administratively: " + e, e);
+            throw new RuntimeException("Could not log in to repository (" + e
+                    + ")", e);
+        } catch (PersistenceException e) {
+            logger.error("handleEvent: got a PersistenceException: " + e, e);
+            throw new RuntimeException(
+                    "Exception while talking to repository (" + e + ")", e);
+        } finally {
+            if (resourceResolver != null) {
+                resourceResolver.close();
+            }
+        }
+
+        logger.debug("doUpdateProperties: updating properties done.");
+    }
+
+    /**
+     * Update the properties and sent a topology event if applicable
+     */
+    public void updateProperties() {
+        synchronized (lock) {
+            logger.debug("updateProperties: calling doUpdateProperties.");
+            doUpdateProperties();
+            logger.debug("updateProperties: calling handlePotentialTopologyChange.");
+            handlePotentialTopologyChange();
+            logger.debug("updateProperties: done.");
+        }
+    }
+
+    /**
+     * Internal class caching some provider infos like service id and ranking.
+     */
+    private final static class ProviderInfo implements Comparable<ProviderInfo> {
+
+        public final PropertyProvider provider;
+        public final Object propertyProperties;
+        public final int ranking;
+        public final long serviceId;
+        public final Map<String, String> properties = new HashMap<String, String>();
+
+        public ProviderInfo(final PropertyProvider provider,
+                final Map<String, Object> serviceProps) {
+            this.provider = provider;
+            this.propertyProperties = serviceProps.get(PropertyProvider.PROPERTY_PROPERTIES);
+            final Object sr = serviceProps.get(Constants.SERVICE_RANKING);
+            if (sr == null || !(sr instanceof Integer)) {
+                this.ranking = 0;
+            } else {
+                this.ranking = (Integer) sr;
+            }
+            this.serviceId = (Long) serviceProps.get(Constants.SERVICE_ID);
+            refreshProperties();
+        }
+
+        public void refreshProperties() {
+            properties.clear();
+            if (this.propertyProperties instanceof String) {
+                final String val = provider.getProperty((String) this.propertyProperties);
+                if (val != null) {
+                	putPropertyIfValid((String) this.propertyProperties, val);
+                }
+            } else if (this.propertyProperties instanceof String[]) {
+                for (final String name : (String[]) this.propertyProperties) {
+                    final String val = provider.getProperty(name);
+                    if (val != null) {
+                        putPropertyIfValid(name, val);
+                    }
+                }
+            }
+        }
+
+        /** SLING-2883 : put property only if valid **/
+		private void putPropertyIfValid(final String name, final String val) {
+			if (PropertyNameHelper.isValidPropertyName(name)) {
+				this.properties.put(name, val);
+			}
+		}
+
+		/**
+         * @see java.lang.Comparable#compareTo(java.lang.Object)
+         */
+        public int compareTo(final ProviderInfo o) {
+            // Sort by rank in ascending order.
+            if (this.ranking < o.ranking) {
+                return -1; // lower rank
+            } else if (this.ranking > o.ranking) {
+                return 1; // higher rank
+            }
+            // If ranks are equal, then sort by service id in descending order.
+            return (this.serviceId < o.serviceId) ? 1 : -1;
+        }
+
+        @Override
+        public boolean equals(final Object obj) {
+            if (obj instanceof ProviderInfo) {
+                return ((ProviderInfo) obj).serviceId == this.serviceId;
+            }
+            return false;
+        }
+
+        @Override
+        public int hashCode() {
+            return provider.hashCode();
+        }
+    }
+
+    /**
+     * Handle the fact that the topology has likely changed
+     */
+    public void handlePotentialTopologyChange() {
+        viewStateManagerLock.lock();
+        try{
+            if (!activated) {
+                logger.debug("handlePotentialTopologyChange: not yet activated, ignoring");
+                return;
+            }
+            BaseTopologyView t = (BaseTopologyView) getTopology();
+            if (t.isCurrent()) {
+                // if we have a valid view, let the viewStateManager do the
+                // comparison and sending of an event, if necessary
+                viewStateManager.handleNewView(t);
+            } else {
+                // if we don't have a view, then we might have to send
+                // a CHANGING event, let that be decided by the viewStateManager as well
+                viewStateManager.handleChanging();
+            }
+        } finally {
+            if (viewStateManagerLock!=null) {
+                viewStateManagerLock.unlock();
+            }
+        }
+    }
+
+    /**
+     * Handle the fact that the topology has started to change - inform the listeners asap
+     */
+    public void handleTopologyChanging() {
+        logger.debug("handleTopologyChanging: invoking viewStateManager.handlechanging");
+        viewStateManager.handleChanging();
+    }
+
+    protected ClusterViewService getClusterViewService() {
+        return clusterViewService;
+    }
+    
+    protected AnnouncementRegistry getAnnouncementRegistry() {
+        return announcementRegistry;
+    }
+
+    /** for testing only 
+     * @return */
+    public ViewStateManager getViewStateManager() {
+        return viewStateManager;
+    }
+
+}

Propchange: sling/trunk/bundles/extensions/discovery/oak/src/main/java/org/apache/sling/discovery/oak/OakDiscoveryService.java
------------------------------------------------------------------------------
    svn:eol-style = native