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.message;
018
019import java.io.InvalidObjectException;
020import java.io.ObjectInputStream;
021import java.io.Serializable;
022import java.lang.management.ManagementFactory;
023import java.lang.management.ThreadInfo;
024import java.lang.management.ThreadMXBean;
025import java.lang.reflect.Method;
026import java.util.HashMap;
027import java.util.Map;
028
029import org.apache.logging.log4j.util.StringBuilderFormattable;
030import org.apache.logging.log4j.util.Strings;
031
032/**
033 * Captures information about all running Threads.
034 */
035@AsynchronouslyFormattable
036public class ThreadDumpMessage implements Message, StringBuilderFormattable {
037
038    private static final long serialVersionUID = -1103400781608841088L;
039
040    private static final ThreadInfoFactory FACTORY;
041
042    private volatile Map<ThreadInformation, StackTraceElement[]> threads;
043
044    private final String title;
045
046    private String formattedMessage;
047
048    static {
049        final Method[] methods = ThreadInfo.class.getMethods();
050        boolean basic = true;
051        for (final Method method : methods) {
052            if (method.getName().equals("getLockInfo")) {
053                basic = false;
054                break;
055            }
056        }
057        FACTORY = basic ? new BasicThreadInfoFactory() : new ExtendedThreadInfoFactory();
058    }
059
060    /**
061     * Generate a ThreadDumpMessage with a title.
062     * @param title The title.
063     */
064    public ThreadDumpMessage(final String title) {
065        this.title = title == null ? Strings.EMPTY : title;
066        threads = FACTORY.createThreadInfo();
067    }
068
069    private ThreadDumpMessage(final String formattedMsg, final String title) {
070        this.formattedMessage = formattedMsg;
071        this.title = title == null ? Strings.EMPTY : title;
072    }
073
074    @Override
075    public String toString() {
076        return getFormattedMessage();
077    }
078
079    /**
080     * Returns the ThreadDump in printable format.
081     * @return the ThreadDump suitable for logging.
082     */
083    @Override
084    public String getFormattedMessage() {
085        if (formattedMessage != null) {
086            return formattedMessage;
087        }
088        final StringBuilder sb = new StringBuilder(255);
089        formatTo(sb);
090        return sb.toString();
091    }
092
093    @Override
094    public void formatTo(final StringBuilder sb) {
095        sb.append(title);
096        if (title.length() > 0) {
097            sb.append('\n');
098        }
099        for (final Map.Entry<ThreadInformation, StackTraceElement[]> entry : threads.entrySet()) {
100            final ThreadInformation info = entry.getKey();
101            info.printThreadInfo(sb);
102            info.printStack(sb, entry.getValue());
103            sb.append('\n');
104        }
105    }
106
107    /**
108     * Returns the title.
109     * @return the title.
110     */
111    @Override
112    public String getFormat() {
113        return title == null ? Strings.EMPTY : title;
114    }
115
116    /**
117     * Returns an array with a single element, a Map containing the ThreadInformation as the key.
118     * and the StackTraceElement array as the value;
119     * @return the "parameters" to this Message.
120     */
121    @Override
122    public Object[] getParameters() {
123        return null;
124    }
125
126        /**
127     * Creates a ThreadDumpMessageProxy that can be serialized.
128     * @return a ThreadDumpMessageProxy.
129     */
130    protected Object writeReplace() {
131        return new ThreadDumpMessageProxy(this);
132    }
133
134    private void readObject(final ObjectInputStream stream)
135        throws InvalidObjectException {
136        throw new InvalidObjectException("Proxy required");
137    }
138
139    /**
140     * Proxy pattern used to serialize the ThreadDumpMessage.
141     */
142    private static class ThreadDumpMessageProxy implements Serializable {
143
144        private static final long serialVersionUID = -3476620450287648269L;
145        private final String formattedMsg;
146        private final String title;
147
148        ThreadDumpMessageProxy(final ThreadDumpMessage msg) {
149            this.formattedMsg = msg.getFormattedMessage();
150            this.title = msg.title;
151        }
152
153        /**
154         * Returns a ThreadDumpMessage using the data in the proxy.
155         * @return a ThreadDumpMessage.
156         */
157        protected Object readResolve() {
158            return new ThreadDumpMessage(formattedMsg, title);
159        }
160    }
161
162    /**
163     * Factory to create Thread information.
164     */
165    private interface ThreadInfoFactory {
166        Map<ThreadInformation, StackTraceElement[]> createThreadInfo();
167    }
168
169    /**
170     * Factory to create basic thread information.
171     */
172    private static class BasicThreadInfoFactory implements ThreadInfoFactory {
173        @Override
174        public Map<ThreadInformation, StackTraceElement[]> createThreadInfo() {
175            final Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
176            final Map<ThreadInformation, StackTraceElement[]> threads =
177                new HashMap<>(map.size());
178            for (final Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
179                threads.put(new BasicThreadInformation(entry.getKey()), entry.getValue());
180            }
181            return threads;
182        }
183    }
184
185    /**
186     * Factory to create extended thread information.
187     */
188    private static class ExtendedThreadInfoFactory implements ThreadInfoFactory {
189        @Override
190        public Map<ThreadInformation, StackTraceElement[]> createThreadInfo() {
191            final ThreadMXBean bean = ManagementFactory.getThreadMXBean();
192            final ThreadInfo[] array = bean.dumpAllThreads(true, true);
193
194            final Map<ThreadInformation, StackTraceElement[]>  threads =
195                new HashMap<>(array.length);
196            for (final ThreadInfo info : array) {
197                threads.put(new ExtendedThreadInformation(info), info.getStackTrace());
198            }
199            return threads;
200        }
201    }
202
203    /**
204     * Always returns null.
205     *
206     * @return null
207     */
208    @Override
209    public Throwable getThrowable() {
210        return null;
211    }
212}