001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017
018package org.apache.logging.log4j.core.osgi;
019
020import java.util.Collection;
021import java.util.Hashtable;
022import java.util.concurrent.atomic.AtomicReference;
023
024import org.apache.logging.log4j.LogManager;
025import org.apache.logging.log4j.Logger;
026import org.apache.logging.log4j.core.config.plugins.util.PluginRegistry;
027import org.apache.logging.log4j.core.impl.Log4jProvider;
028import org.apache.logging.log4j.core.impl.ThreadContextDataInjector;
029import org.apache.logging.log4j.core.impl.ThreadContextDataProvider;
030import org.apache.logging.log4j.core.util.Constants;
031import org.apache.logging.log4j.core.util.ContextDataProvider;
032import org.apache.logging.log4j.spi.Provider;
033import org.apache.logging.log4j.status.StatusLogger;
034import org.apache.logging.log4j.util.PropertiesUtil;
035import org.osgi.framework.Bundle;
036import org.osgi.framework.BundleActivator;
037import org.osgi.framework.BundleContext;
038import org.osgi.framework.BundleEvent;
039import org.osgi.framework.InvalidSyntaxException;
040import org.osgi.framework.ServiceReference;
041import org.osgi.framework.ServiceRegistration;
042import org.osgi.framework.SynchronousBundleListener;
043import org.osgi.framework.wiring.BundleWiring;
044
045/**
046 * OSGi BundleActivator.
047 */
048public final class Activator implements BundleActivator, SynchronousBundleListener {
049
050    private static final Logger LOGGER = StatusLogger.getLogger();
051
052    private final AtomicReference<BundleContext> contextRef = new AtomicReference<>();
053
054    ServiceRegistration provideRegistration = null;
055    ServiceRegistration contextDataRegistration = null;
056
057    @Override
058    public void start(final BundleContext context) throws Exception {
059        final Provider provider = new Log4jProvider();
060        final Hashtable<String, String> props = new Hashtable<>();
061        props.put("APIVersion", "2.60");
062        final ContextDataProvider threadContextProvider = new ThreadContextDataProvider();
063        provideRegistration = context.registerService(Provider.class.getName(), provider, props);
064        contextDataRegistration = context.registerService(ContextDataProvider.class.getName(), threadContextProvider,
065                null);
066        loadContextProviders(context);
067        // allow the user to override the default ContextSelector (e.g., by using BasicContextSelector for a global cfg)
068        if (PropertiesUtil.getProperties().getStringProperty(Constants.LOG4J_CONTEXT_SELECTOR) == null) {
069            System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, BundleContextSelector.class.getName());
070        }
071        if (this.contextRef.compareAndSet(null, context)) {
072            context.addBundleListener(this);
073            // done after the BundleListener as to not miss any new bundle installs in the interim
074            scanInstalledBundlesForPlugins(context);
075        }
076    }
077
078    private static void scanInstalledBundlesForPlugins(final BundleContext context) {
079        final Bundle[] bundles = context.getBundles();
080        for (final Bundle bundle : bundles) {
081            // TODO: bundle state can change during this
082            scanBundleForPlugins(bundle);
083        }
084    }
085
086    private static void scanBundleForPlugins(final Bundle bundle) {
087        final long bundleId = bundle.getBundleId();
088        // LOG4J2-920: don't scan system bundle for plugins
089        if (bundle.getState() == Bundle.ACTIVE && bundleId != 0) {
090            LOGGER.trace("Scanning bundle [{}, id=%d] for plugins.", bundle.getSymbolicName(), bundleId);
091            PluginRegistry.getInstance().loadFromBundle(bundleId,
092                    bundle.adapt(BundleWiring.class).getClassLoader());
093        }
094    }
095
096    private static void loadContextProviders(final BundleContext bundleContext) {
097        try {
098            final Collection<ServiceReference<ContextDataProvider>> serviceReferences =
099                    bundleContext.getServiceReferences(ContextDataProvider.class, null);
100            for (final ServiceReference<ContextDataProvider> serviceReference : serviceReferences) {
101                final ContextDataProvider provider = bundleContext.getService(serviceReference);
102                ThreadContextDataInjector.contextDataProviders.add(provider);
103            }
104        } catch (final InvalidSyntaxException ex) {
105            LOGGER.error("Error accessing context data provider", ex);
106        }
107    }
108
109    private static void stopBundlePlugins(final Bundle bundle) {
110        LOGGER.trace("Stopping bundle [{}] plugins.", bundle.getSymbolicName());
111        // TODO: plugin lifecycle code
112        PluginRegistry.getInstance().clearBundlePlugins(bundle.getBundleId());
113    }
114
115    @Override
116    public void stop(final BundleContext context) throws Exception {
117        provideRegistration.unregister();
118        contextDataRegistration.unregister();
119        this.contextRef.compareAndSet(context, null);
120        LogManager.shutdown();
121    }
122
123    @Override
124    public void bundleChanged(final BundleEvent event) {
125        switch (event.getType()) {
126            // FIXME: STARTING instead of STARTED?
127            case BundleEvent.STARTED:
128                scanBundleForPlugins(event.getBundle());
129                break;
130
131            case BundleEvent.STOPPING:
132                stopBundlePlugins(event.getBundle());
133                break;
134
135            default:
136                break;
137        }
138    }
139}