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 */
017package org.apache.logging.log4j.util;
018
019import java.io.IOException;
020import java.lang.invoke.MethodHandles;
021import java.net.URL;
022import java.util.Collection;
023import java.util.Enumeration;
024import java.util.HashSet;
025import java.util.Properties;
026import java.util.ServiceLoader;
027import java.util.concurrent.locks.Lock;
028import java.util.concurrent.locks.ReentrantLock;
029
030import org.apache.logging.log4j.Logger;
031import org.apache.logging.log4j.spi.Provider;
032import org.apache.logging.log4j.status.StatusLogger;
033
034/**
035 * <em>Consider this class private.</em> Utility class for Log4j {@link Provider}s. When integrating with an application
036 * container framework, any Log4j Providers not accessible through standard classpath scanning should
037 * {@link #loadProvider(java.net.URL, ClassLoader)} a classpath accordingly.
038 */
039public final class ProviderUtil {
040
041    /**
042     * Resource name for a Log4j 2 provider properties file.
043     */
044    protected static final String PROVIDER_RESOURCE = "META-INF/log4j-provider.properties";
045
046    /**
047     * Loaded providers.
048     */
049    protected static final Collection<Provider> PROVIDERS = new HashSet<>();
050
051    /**
052     * Guards the ProviderUtil singleton instance from lazy initialization. This is primarily used for OSGi support.
053     *
054     * @since 2.1
055     */
056    protected static final Lock STARTUP_LOCK = new ReentrantLock();
057
058    private static final String API_VERSION = "Log4jAPIVersion";
059    private static final String[] COMPATIBLE_API_VERSIONS = {"2.6.0"};
060    private static final Logger LOGGER = StatusLogger.getLogger();
061
062    // STARTUP_LOCK guards INSTANCE for lazy initialization; this allows the OSGi Activator to pause the startup and
063    // wait for a Provider to be installed. See LOG4J2-373
064    private static volatile ProviderUtil instance;
065
066    private ProviderUtil() {
067        ServiceLoaderUtil.loadServices(Provider.class, MethodHandles.lookup(), false)
068                .filter(provider -> validVersion(provider.getVersions()))
069                .forEach(PROVIDERS::add);
070
071        for (final LoaderUtil.UrlResource resource : LoaderUtil.findUrlResources(PROVIDER_RESOURCE, false)) {
072            loadProvider(resource.getUrl(), resource.getClassLoader());
073        }
074    }
075
076    protected static void addProvider(final Provider provider) {
077        PROVIDERS.add(provider);
078        LOGGER.debug("Loaded Provider {}", provider);
079    }
080
081    /**
082     * Loads an individual Provider implementation. This method is really only useful for the OSGi bundle activator and
083     * this class itself.
084     *
085     * @param url the URL to the provider properties file
086     * @param cl the ClassLoader to load the provider classes with
087     */
088    protected static void loadProvider(final URL url, final ClassLoader cl) {
089        try {
090            final Properties props = PropertiesUtil.loadClose(url.openStream(), url);
091            if (validVersion(props.getProperty(API_VERSION))) {
092                final Provider provider = new Provider(props, url, cl);
093                PROVIDERS.add(provider);
094                LOGGER.debug("Loaded Provider {}", provider);
095            }
096        } catch (final IOException e) {
097            LOGGER.error("Unable to open {}", url, e);
098        }
099    }
100
101    /**
102     * 
103     * @param classLoader null can be used to mark the bootstrap class loader.
104     */
105    protected static void loadProviders(final ClassLoader classLoader) {
106        ServiceLoaderUtil.loadClassloaderServices(Provider.class, MethodHandles.lookup(), classLoader, true)
107                .filter(provider -> validVersion(provider.getVersions()))
108                .forEach(PROVIDERS::add);
109    }
110
111    /**
112     * @deprecated Use {@link #loadProvider(java.net.URL, ClassLoader)} instead. Will be removed in 3.0.
113     */
114    @Deprecated
115    protected static void loadProviders(final Enumeration<URL> urls, final ClassLoader cl) {
116        if (urls != null) {
117            while (urls.hasMoreElements()) {
118                loadProvider(urls.nextElement(), cl);
119            }
120        }
121    }
122
123    public static Iterable<Provider> getProviders() {
124        lazyInit();
125        return PROVIDERS;
126    }
127
128    public static boolean hasProviders() {
129        lazyInit();
130        return !PROVIDERS.isEmpty();
131    }
132
133    /**
134     * Lazily initializes the ProviderUtil singleton.
135     *
136     * @since 2.1
137     */
138    protected static void lazyInit() {
139        // noinspection DoubleCheckedLocking
140        if (instance == null) {
141            try {
142                STARTUP_LOCK.lockInterruptibly();
143                try {
144                    if (instance == null) {
145                        instance = new ProviderUtil();
146                    }
147                } finally {
148                    STARTUP_LOCK.unlock();
149                }
150            } catch (final InterruptedException e) {
151                LOGGER.fatal("Interrupted before Log4j Providers could be loaded.", e);
152                Thread.currentThread().interrupt();
153            }
154        }
155    }
156
157    public static ClassLoader findClassLoader() {
158        return LoaderUtil.getThreadContextClassLoader();
159    }
160
161    private static boolean validVersion(final String version) {
162        for (final String v : COMPATIBLE_API_VERSIONS) {
163            if (version.startsWith(v)) {
164                return true;
165            }
166        }
167        return false;
168    }
169}