diff --git a/dependencymanager/org.apache.felix.dependencymanager.itest.api/src/org/apache/felix/dm/itest/api/FELIX6886_LateServiceEventTest.java b/dependencymanager/org.apache.felix.dependencymanager.itest.api/src/org/apache/felix/dm/itest/api/FELIX6886_LateServiceEventTest.java new file mode 100644 index 0000000000..1b2462e453 --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager.itest.api/src/org/apache/felix/dm/itest/api/FELIX6886_LateServiceEventTest.java @@ -0,0 +1,209 @@ +/* + * 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.felix.dm.itest.api; + +import java.util.Hashtable; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.felix.dm.Component; +import org.apache.felix.dm.DependencyManager; +import org.apache.felix.dm.context.ComponentContext; +import org.apache.felix.dm.itest.util.TestBase; +import org.osgi.framework.Bundle; +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceFactory; +import org.osgi.framework.ServiceRegistration; + +/** + * FELIX-6886: a service matching an instance-bound dependency shows up while the component instance is being + * destroyed. The dependency tracker obtains the service and sends an event which is queued in the component executor, + * and handled after the instance-bound dependency has been stopped and removed from the component. + *

+ * When the dependency is stopped, closing its tracker sends a REMOVED event for every tracked service. These REMOVED + * events are handled inline (the component executor is run by the current thread) while the dependency is still part + * of the component, and they release the services. The queued events are then ignored: if handling them fails, the + * error is logged and the test fails in {@link TestBase#tearDown()}. + */ +public class FELIX6886_LateServiceEventTest extends TestBase { + + public interface A { + } + + public interface B { + } + + /** + * B service factory counting how many times the service is obtained and released. + */ + static class CountingFactory implements ServiceFactory { + final AtomicInteger m_gets = new AtomicInteger(); + final AtomicInteger m_ungets = new AtomicInteger(); + volatile ServiceRegistration m_registration; + + @Override + public B getService(Bundle bundle, ServiceRegistration registration) { + m_gets.incrementAndGet(); + return new B() { + }; + } + + @Override + public void ungetService(Bundle bundle, ServiceRegistration registration, B service) { + m_ungets.incrementAndGet(); + } + + void unregister() { + if (m_registration != null) { + m_registration.unregister(); + } + } + } + + /** + * Component with an instance-bound dependency on B, added from init(). The destroy callback runs the given action, + * before the instance-bound dependency is stopped. + */ + public static class Consumer { + private final Runnable m_onDestroy; + + Consumer(Runnable onDestroy) { + m_onDestroy = onDestroy; + } + + void init(Component c) { + DependencyManager dm = c.getDependencyManager(); + // The swap callback is required: without it, the tracker sends ADDED + REMOVED events instead of a + // SWAPPED event when an aspect replaces the original service. + c.add(dm.createServiceDependency().setService(B.class).setRequired(false) + .setCallbacks("bind", null, "unbind", "swap")); + } + + void destroy() { + m_onDestroy.run(); + } + + void bind(B b) { + } + + void unbind(B b) { + } + + void swap(B oldB, B newB) { + } + } + + // Registration of the A service, required by the consumer. + private ServiceRegistration m_regA; + + /** + * A B service is registered while the instance is being destroyed: the tracker sends an ADDED event, which is + * queued and handled after the dependency has been removed from the component. + */ + public void testAddedEventQueuedBeforeTrackerClose() { + CountingFactory b = new CountingFactory(); + Component c = startConsumer(/* onDestroy */ () -> registerFromAnotherThread(b, new Hashtable<>())); + try { + destroyInstance(c); + assertReleased(b); + } finally { + getDM().remove(c); + b.unregister(); + } + } + + /** + * A B service is bound to the dependency, and an aspect of this service is registered while the instance is being + * destroyed: the tracker replaces the original service by the aspect and sends a SWAPPED event, which is queued and + * handled after the dependency has been removed from the component. + */ + public void testSwappedEventQueuedBeforeTrackerClose() { + CountingFactory b = new CountingFactory(); + CountingFactory aspect = new CountingFactory(); + register(b, new Hashtable<>()); + Component c = startConsumer(/* onDestroy */ () -> registerFromAnotherThread(aspect, aspectOf(b))); + try { + destroyInstance(c); + assertReleased(b); + assertReleased(aspect); + } finally { + getDM().remove(c); + aspect.unregister(); + b.unregister(); + } + } + + /** + * Starts a consumer component, and makes it available by registering the A service it requires. + */ + private Component startConsumer(Runnable onDestroy) { + DependencyManager m = getDM(); + Component c = m.createComponent() + .setImplementation(new Consumer(onDestroy)) + .add(m.createServiceDependency().setService(A.class).setRequired(true)); + m.add(c); + m_regA = context.registerService(A.class.getName(), new A() { + }, null); + assertTrue(((ComponentContext) c).isAvailable()); + return c; + } + + /** + * Unregisters the A service: the consumer instance is destroyed and its instance-bound dependency is stopped. + * All events are handled when this method returns: the component executor is run by the current thread, which also + * handles the events queued by other threads in the meantime. + */ + private void destroyInstance(Component c) { + m_regA.unregister(); + assertFalse(((ComponentContext) c).isAvailable()); + } + + private void register(CountingFactory factory, Hashtable properties) { + factory.m_registration = context.registerService(B.class.getName(), factory, properties); + } + + private void registerFromAnotherThread(CountingFactory factory, Hashtable properties) { + Thread t = new Thread(() -> register(factory, properties)); + t.start(); + try { + t.join(10_000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError("interrupted while registering the service", e); + } + if (t.isAlive()) { + throw new AssertionError("the service has not been registered"); + } + } + + /** + * Returns the service properties of an aspect of the given service, with a higher ranking. + */ + private static Hashtable aspectOf(CountingFactory original) { + Hashtable props = new Hashtable<>(); + props.put(DependencyManager.ASPECT, original.m_registration.getReference().getProperty(Constants.SERVICE_ID)); + props.put(Constants.SERVICE_RANKING, 10); + return props; + } + + private static void assertReleased(CountingFactory factory) { + assertTrue("the service has not been obtained by the dependency tracker", factory.m_gets.get() > 0); + assertEquals("the service obtained by the removed dependency has not been released", + factory.m_gets.get(), factory.m_ungets.get()); + } +} diff --git a/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/ComponentImpl.java b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/ComponentImpl.java index 5a44379682..850fdd89c2 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/ComponentImpl.java +++ b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/ComponentImpl.java @@ -1316,9 +1316,12 @@ private void handleAdded(DependencyContext dc, Event e) { return; } m_logger.debug("handleAdded %s", e); - + Set dependencyEvents = m_dependencyEvents.get(dc); - dependencyEvents.add(e); + if (dependencyEvents == null) { + return; // the dependency has been removed from the component + } + dependencyEvents.add(e); dc.setAvailable(true); // In the following switch block, we sometimes only recalculate state changes @@ -1364,6 +1367,9 @@ private void handleChanged(final DependencyContext dc, final Event e) { return; } Set dependencyEvents = m_dependencyEvents.get(dc); + if (dependencyEvents == null) { + return; // the dependency has been removed from the component + } dependencyEvents.remove(e); dependencyEvents.add(e); @@ -1394,6 +1400,9 @@ private void handleRemoved(DependencyContext dc, Event e) { } // Check if the dependency is still available. Set dependencyEvents = m_dependencyEvents.get(dc); + if (dependencyEvents == null) { + return; // the dependency has been removed from the component + } int size = dependencyEvents.size(); if (dependencyEvents.contains(e)) { size--; // the dependency is currently registered and is about to be removed. @@ -1435,7 +1444,10 @@ private void handleSwapped(DependencyContext dc, Event oldEvent, Event newEvent) if (! m_isStarted) { return; } - Set dependencyEvents = m_dependencyEvents.get(dc); + Set dependencyEvents = m_dependencyEvents.get(dc); + if (dependencyEvents == null) { + return; // the dependency has been removed from the component + } dependencyEvents.remove(oldEvent); dependencyEvents.add(newEvent); @@ -1757,6 +1769,11 @@ private void removeInstanceBoundDependencies() { m_dependencies.remove(dep); generateNameBasedOnServiceAndProperties(); dep.stop(); + // The dependency is no longer part of this component: release its events. + Set events = m_dependencyEvents.remove(dep); + if (events != null) { + events.forEach(Event::close); + } } } } diff --git a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6886_InstanceBoundDependencyLeakTest.java b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6886_InstanceBoundDependencyLeakTest.java new file mode 100644 index 0000000000..a48b462ffa --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6886_InstanceBoundDependencyLeakTest.java @@ -0,0 +1,165 @@ +/* + * 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 test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.felix.dm.Component; +import org.apache.felix.dm.impl.ComponentImpl; +import org.junit.Assert; +import org.junit.Test; + +/** + * FELIX-6886: dependencies added from the init() callback (instance-bound dependencies) are removed from the + * component when its instance is destroyed. No reference to their events must be kept afterwards, as it is the + * case when a dependency is removed with Component.remove(Dependency). + */ +public class FELIX6886_InstanceBoundDependencyLeakTest { + private static final int CYCLES = 100; + + /** + * Event which counts how many times it is closed. + */ + static class ClosableEvent extends EventImpl { + final AtomicInteger m_closed = new AtomicInteger(); + + @Override + public void close() { + m_closed.incrementAndGet(); + } + } + + @Test + public void testInstanceBoundDependencyEventsAreReleasedOnDestroy() { + final List instanceBoundDeps = new ArrayList<>(); + final List instanceBoundEvents = new ArrayList<>(); + final SimpleServiceDependency required = new SimpleServiceDependency(); + required.setRequired(true); + + ComponentImpl c = new ComponentImpl(); + c.setImplementation(new Object() { + @SuppressWarnings("unused") + void init(Component comp) { + SimpleServiceDependency dep = new SimpleServiceDependency(); + dep.setRequired(false); + instanceBoundDeps.add(dep); + comp.add(dep); + ClosableEvent event = new ClosableEvent(); + instanceBoundEvents.add(event); + dep.add(event); + } + }); + c.add(required); + c.start(); + + EventImpl requiredEvent = new EventImpl(1); + for (int i = 0; i < CYCLES; i++) { + // the required dependency comes up: the instance is created and init() adds a new dependency + required.add(requiredEvent); + Assert.assertTrue(c.isAvailable()); + // the required dependency goes away: the instance is destroyed with its instance-bound dependency + required.remove(requiredEvent); + Assert.assertFalse(c.isAvailable()); + } + + Assert.assertEquals(CYCLES, instanceBoundDeps.size()); + int leaked = 0; + for (SimpleServiceDependency dep : instanceBoundDeps) { + if (c.getDependencyEvents(dep) != null) { + leaked++; + } + } + int notClosed = 0; + for (ClosableEvent event : instanceBoundEvents) { + if (event.m_closed.get() == 0) { + notClosed++; + } + } + c.stop(); + Assert.assertEquals("events of removed instance-bound dependencies are still referenced", 0, leaked); + Assert.assertEquals("events of removed instance-bound dependencies are not closed", 0, notClosed); + } + + @Test + public void testRemovedEventAfterInstanceBoundDependencyRemoval() { + // Like a service tracker being closed, the dependency sends a REMOVED event when it is stopped. Since the + // dependency is stopped from the component executor, this event is handled after the dependency has been + // removed from the component. + final List instanceBoundDeps = new ArrayList<>(); + final List instanceBoundEvents = new ArrayList<>(); + final SimpleServiceDependency required = new SimpleServiceDependency(); + required.setRequired(true); + + ComponentImpl c = new ComponentImpl(); + c.setImplementation(new Object() { + @SuppressWarnings("unused") + void init(Component comp) { + final ClosableEvent event = new ClosableEvent(); + SimpleServiceDependency dep = new SimpleServiceDependency() { + @Override + public void stop() { + super.stop(); + remove(event); + } + }; + dep.setRequired(false); + instanceBoundDeps.add(dep); + instanceBoundEvents.add(event); + comp.add(dep); + dep.add(event); + } + }); + c.add(required); + c.start(); + + EventImpl requiredEvent = new EventImpl(1); + for (int i = 0; i < 2; i++) { + required.add(requiredEvent); + Assert.assertTrue(c.isAvailable()); + required.remove(requiredEvent); + Assert.assertFalse(c.isAvailable()); + } + + for (int i = 0; i < instanceBoundDeps.size(); i++) { + Assert.assertNull(c.getDependencyEvents(instanceBoundDeps.get(i))); + Assert.assertTrue(instanceBoundEvents.get(i).m_closed.get() > 0); + } + c.stop(); + } + + @Test + public void testDependencyEventsAreReleasedOnRemove() { + // reference behavior: a dependency removed with Component.remove(Dependency) leaves no events behind + SimpleServiceDependency dep = new SimpleServiceDependency(); + dep.setRequired(false); + + ComponentImpl c = new ComponentImpl(); + c.setImplementation(new Object()); + c.add(dep); + c.start(); + dep.add(new EventImpl(1)); + Assert.assertNotNull(c.getDependencyEvents(dep)); + + c.remove(dep); + Assert.assertNull(c.getDependencyEvents(dep)); + c.stop(); + } +} diff --git a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6886_LateAddedServiceTest.java b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6886_LateAddedServiceTest.java new file mode 100644 index 0000000000..8a940b4a6b --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6886_LateAddedServiceTest.java @@ -0,0 +1,117 @@ +/* + * 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 test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.apache.felix.dm.Component; +import org.apache.felix.dm.Logger; +import org.apache.felix.dm.context.ComponentContext; +import org.apache.felix.dm.impl.ComponentImpl; +import org.apache.felix.dm.impl.ServiceEventImpl; +import org.junit.Assert; +import org.junit.Test; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; + +/** + * FELIX-6886: an ADDED event sent by an instance-bound dependency while it is being stopped is handled after the + * dependency has been removed from the component. The service held by this event must be released. + *

+ * The queued ADDED event is ignored, since the dependency has been removed from the component: handling it must not + * fail. Like a service tracker, the dependency then sends a REMOVED event for the service it has added (same event + * object), and this REMOVED event releases the service, even though the dependency has been removed from the + * component. + */ +public class FELIX6886_LateAddedServiceTest { + @Test + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void lateAddedServiceQueuedDuringStopIsReleased() throws Exception { + BundleContext bundleContext = mock(BundleContext.class); + ComponentContext componentContext = mock(ComponentContext.class); + ServiceReference reference = mock(ServiceReference.class); + when(componentContext.getBundleContext()).thenReturn(bundleContext); + ServiceEventImpl lateEvent = new ServiceEventImpl(componentContext, reference, new Object()); + + // Errors thrown while the component executor handles an event are only logged: collect them. + List errors = new CopyOnWriteArrayList<>(); + Logger logger = new Logger(null) { + @Override + protected void doLog(ServiceReference sr, int level, String msg, Throwable throwable) { + if (level == LOG_ERROR) { + errors.add(msg + (throwable != null ? " (" + throwable + ")" : "")); + } + super.doLog(sr, level, msg, throwable); + } + }; + + SimpleServiceDependency required = new SimpleServiceDependency(); + required.setRequired(true); + + SimpleServiceDependency lateDependency = new SimpleServiceDependency() { + @Override + public void stop() { + super.stop(); + // The late service is added from another thread while the dependency is being stopped: the ADDED + // event is queued, since the component executor is currently run by the current thread. + Thread sender = new Thread(() -> add(lateEvent)); + sender.start(); + try { + sender.join(10_000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + if (sender.isAlive()) { + throw new AssertionError("late ADDED event was not queued"); + } + } + }; + lateDependency.setRequired(false); + + ComponentImpl component = new ComponentImpl(null, null, logger); + component.setImplementation(new Object() { + @SuppressWarnings("unused") + void init(Component comp) { + comp.add(lateDependency); + } + }); + component.add(required); + component.start(); + + EventImpl requiredEvent = new EventImpl(1); + required.add(requiredEvent); + // The instance is destroyed: the late ADDED event is queued while its dependency is being stopped, and ignored. + required.remove(requiredEvent); + + // Like a service tracker, the dependency sends a REMOVED event for the service it has added. + lateDependency.remove(lateEvent); + + Assert.assertEquals("errors logged while handling events", "[]", errors.toString()); + Assert.assertNull(component.getDependencyEvents(lateDependency)); + verify(bundleContext, times(1)).ungetService(reference); + component.stop(); + } +}