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>
034 * Utility class for Log4j {@link Provider}s. When integrating with an application container framework, any Log4j
035 * Providers not accessible through standard classpath scanning should {@link #loadProvider(java.net.URL, ClassLoader)}
036 * 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    private static final String API_VERSION = "Log4jAPIVersion";
045
046    private static final String[] COMPATIBLE_API_VERSIONS = {
047        "2.0.0", "2.1.0"
048    };
049
050    private static final Logger LOGGER = StatusLogger.getLogger();
051
052    protected static final Collection<Provider> PROVIDERS = new HashSet<Provider>();
053
054    /**
055     * Guards the ProviderUtil singleton instance from lazy initialization. This is primarily used for OSGi support.
056     *
057     * @since 2.1
058     */
059    protected static final Lock STARTUP_LOCK = new ReentrantLock();
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
072     * and 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                PROVIDERS.add(new Provider(props, url, cl));
082            }
083        } catch (final IOException e) {
084            LOGGER.error("Unable to open {}", url, e);
085        }
086    }
087
088    /**
089     * @deprecated Use {@link #loadProvider(java.net.URL, ClassLoader)} instead. Will be removed in 3.0.
090     */
091    @Deprecated
092    protected static void loadProviders(final Enumeration<URL> urls, final ClassLoader cl) {
093        if (urls != null) {
094            while (urls.hasMoreElements()) {
095                loadProvider(urls.nextElement(), cl);
096            }
097        }
098    }
099
100    public static Iterable<Provider> getProviders() {
101        lazyInit();
102        return PROVIDERS;
103    }
104
105    public static boolean hasProviders() {
106        lazyInit();
107        return !PROVIDERS.isEmpty();
108    }
109
110    /**
111     * Lazily initializes the ProviderUtil singleton.
112     *
113     * @since 2.1
114     */
115    protected static void lazyInit() {
116        //noinspection DoubleCheckedLocking
117        if (INSTANCE == null) {
118            try {
119                STARTUP_LOCK.lockInterruptibly();
120                try {
121                    if (INSTANCE == null) {
122                        INSTANCE = new ProviderUtil();
123                    }
124                } finally {
125                    STARTUP_LOCK.unlock();
126                }
127            } catch (final InterruptedException e) {
128                LOGGER.fatal("Interrupted before Log4j Providers could be loaded.", e);
129                Thread.currentThread().interrupt();
130            }
131        }
132    }
133
134    public static ClassLoader findClassLoader() {
135        return LoaderUtil.getThreadContextClassLoader();
136    }
137
138    private static boolean validVersion(final String version) {
139        for (final String v : COMPATIBLE_API_VERSIONS) {
140            if (version.startsWith(v)) {
141                return true;
142            }
143        }
144        return false;
145    }
146}