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