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