001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.commons.surveillance;
020
021import java.io.IOException;
022import java.lang.management.ManagementFactory;
023
024import javax.management.MBeanServer;
025
026import lucee.commons.io.SystemUtil;
027import lucee.commons.io.res.Resource;
028import lucee.commons.io.res.type.file.FileResource;
029
030import com.sun.management.HotSpotDiagnosticMXBean;
031
032public class HeapDumper {
033        
034        /**
035         * Dumps the heap to the outputFile file in the same format as the hprof heap dump.
036         * If this method is called remotely from another process, the heap dump output is written to a file named outputFile on the machine where the target VM is running. If outputFile is a relative path, it is relative to the working directory where the target VM was started.
037         * @param res Resource to write the .hprof file.
038         * @param live  if true dump only live objects i.e. objects that are reachable from others
039         * @throws IOException 
040         */
041        public static void dumpTo(Resource res, boolean live) throws IOException {
042                MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer();
043                HotSpotDiagnosticMXBean mxbean = ManagementFactory.newPlatformMXBeanProxy( mbserver, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class );
044                
045                String path;
046                Resource tmp=null;
047                if(res instanceof FileResource) path=res.getAbsolutePath();
048                else {
049                        tmp=SystemUtil.getTempFile("hprof",false);
050                        path=tmp.getAbsolutePath();
051                }
052                try{
053                        // it only 
054                        mxbean.dumpHeap(path, live);
055                }
056                finally{
057                        if(tmp!=null && tmp.exists()){
058                                tmp.moveTo(res);
059                        }
060                }
061                
062        }
063}