001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.http;
019
020import java.io.File;
021import java.io.IOException;
022import one.profiler.AsyncProfiler;
023import org.apache.yetus.audience.InterfaceAudience;
024import org.slf4j.Logger;
025import org.slf4j.LoggerFactory;
026
027/**
028 * Backend that uses the async-profiler Java API (in-process). Requires the
029 * {@code tools.profiler:async-profiler} JAR and its native library on the classpath.
030 * <p>
031 * This class is intentionally isolated in its own file so that the JVM never loads
032 * {@code one.profiler.AsyncProfiler} on systems where the JAR is absent. It is only instantiated
033 * reflectively from {@link ProfilerBackend#detect} after confirming the class is resolvable.
034 */
035@InterfaceAudience.Private
036final class LibraryBackend implements ProfilerBackend {
037
038  private static final Logger LOG = LoggerFactory.getLogger(LibraryBackend.class);
039
040  @Override
041  public String executeStart(ProfileServlet.ProfileRequest request, File outputFile)
042    throws IOException {
043    String cmd = ProfilerCommandMapper.toLibraryStartCommand(request);
044    return AsyncProfiler.getInstance().execute(cmd);
045  }
046
047  @Override
048  public String executeStop(ProfileServlet.ProfileRequest request, File outputFile)
049    throws IOException {
050    String cmd = ProfilerCommandMapper.toLibraryStopCommand(request, outputFile);
051    return AsyncProfiler.getInstance().execute(cmd);
052  }
053
054  @Override
055  public void destroy() {
056    try {
057      AsyncProfiler.getInstance().execute("stop");
058    } catch (Exception e) {
059      LOG.debug("Best-effort stop on servlet destroy failed (profiler may not have been active)",
060        e);
061    }
062  }
063}