bbotella commented on code in PR #4487:
URL: https://github.com/apache/cassandra/pull/4487#discussion_r2593729274


##########
src/java/org/apache/cassandra/service/AsyncProfilerService.java:
##########
@@ -0,0 +1,373 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.service;
+
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import one.profiler.AsyncProfiler;
+import org.apache.cassandra.config.CassandraRelevantProperties;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.config.DurationSpec;
+import org.apache.cassandra.exceptions.ConfigurationException;
+import org.apache.cassandra.io.util.File;
+
+import static java.lang.String.format;
+import static java.util.stream.Collectors.toList;
+import static 
org.apache.cassandra.config.CassandraRelevantProperties.ASYNC_PROFILER_ENABLED;
+import static 
org.apache.cassandra.config.CassandraRelevantProperties.ASYNC_PROFILER_LOG_DIR;
+
+public class AsyncProfilerService
+{
+    private static final Logger logger = 
LoggerFactory.getLogger(AsyncProfilerService.class);
+
+    private static final EnumSet<AsyncProfilerEvent> VALID_EVENTS = 
EnumSet.allOf(AsyncProfilerEvent.class);
+    private static final EnumSet<AsyncProfilerFormat> VALID_FORMATS = 
EnumSet.allOf(AsyncProfilerFormat.class);
+    private static final Pattern VALID_FILENAME_REGEX_PATTERN = 
Pattern.compile("^[a-zA-Z0-9-]*\\.?[a-zA-Z0-9-]*$");
+
+    public enum AsyncProfilerEvent
+    {
+        cpu("cpu"),
+        alloc("alloc"),
+        lock("lock"),
+        wall("wall"),
+        nativemem("nativemem"),
+        cache_misses("cache-misses");
+
+        private final String name;
+
+        AsyncProfilerEvent(String name)
+        {
+            this.name = name;
+        }
+
+        public String getEvent()
+        {
+            return name;
+        }
+
+        public static String parseEvents(String rawString)
+        {
+            if (rawString == null || rawString.isBlank())
+                throw new IllegalArgumentException("Event can not be null nor 
blank string.");
+
+            try
+            {
+                List<String> processedEvents = new ArrayList<>();
+                for (String rawEvent : rawString.split(","))
+                    
processedEvents.add(AsyncProfilerEvent.valueOf(rawEvent).getEvent());
+
+                return String.join(",", processedEvents);
+            }
+            catch (IllegalArgumentException ex)
+            {
+                throw new IllegalArgumentException(format("Event must be one 
or a combination of %s", VALID_EVENTS));
+            }
+        }
+    }
+
+    public enum AsyncProfilerFormat
+    {
+        flat, traces, collapsed, flamegraph, tree, jfr, otlp;
+
+        public static String parseFormat(String rawFormat)
+        {
+            if (rawFormat == null || rawFormat.isBlank())
+                throw new IllegalArgumentException("Event can not be null nor 
blank string.");
+
+            try
+            {
+                return AsyncProfilerFormat.valueOf(rawFormat).name();
+            }
+            catch (IllegalArgumentException ex)
+            {
+                throw new IllegalArgumentException(format("Format must be one 
of %s", VALID_FORMATS));
+            }
+        }
+    }
+
+    private AsyncProfiler profilerInstance;
+
+    private String logDir;
+
+    public synchronized void enable()
+    {
+        if (isEnabled())
+            return;
+
+        ASYNC_PROFILER_ENABLED.setBoolean(true);
+        maybeInitialize();
+    }
+
+    public synchronized void disable()
+    {
+        if (!isEnabled())
+            return;
+
+        if (isRunning())
+            stop(null);
+
+        ASYNC_PROFILER_ENABLED.setBoolean(false);
+        profilerInstance = null;
+    }
+
+    public synchronized AsyncProfiler maybeInitialize()
+    {
+        if (!ASYNC_PROFILER_ENABLED.getBoolean())
+            throw new IllegalStateException("Async-Profiler is not enabled.");
+
+        // if somebody removes dir while a node runs, just recreate it
+        createLogDir();
+
+        if (profilerInstance == null)
+        {
+            try
+            {
+                profilerInstance = one.profiler.AsyncProfiler.getInstance();
+            }
+            catch (ConfigurationException ex)
+            {
+                throw ex;
+            }
+            catch (Throwable t)
+            {
+                throw new IllegalStateException("Unable to get an instance of 
Async-Profiler", t);
+            }
+        }
+
+        return profilerInstance;
+    }
+
+    public synchronized boolean start(String events, String outputFormat, 
String duration, String outputFileName)
+    {
+        if (isRunning())
+            return false;
+
+        try
+        {
+            String cmd = format("start,%s,event=%s,timeout=%s,file=%s",
+                                AsyncProfilerFormat.parseFormat(outputFormat),
+                                AsyncProfilerEvent.parseEvents(events),
+                                parseDuration(duration),
+                                new File(logDir, 
validateOutputFileName(outputFileName)));
+
+            String result = maybeInitialize().execute(cmd);
+            logger.debug("Started Async-Profiler: result={}, cmd={}", result, 
cmd);
+            return true;
+        }
+        catch (IllegalStateException | IllegalArgumentException ex)
+        {
+            throw ex;
+        }
+        catch (Throwable t)
+        {
+            logger.error("Failed to start Async-Profiler", t);
+            return false;
+        }
+    }
+
+    public synchronized boolean stop(String outputFileName)
+    {
+        if (!isRunning())
+            return false;
+
+        try
+        {
+            String cmd = "stop";
+            if (outputFileName != null)
+            {
+                File outputFile = new File(logDir, 
validateOutputFileName(outputFileName));
+                cmd += ",file=" + outputFile.absolutePath();
+            }
+
+            String result = maybeInitialize().execute(cmd);
+            logger.debug("Stopped Async-Profiler: result={}, cmd={}", result, 
cmd);
+            return true;
+        }
+        catch (IllegalStateException | IllegalArgumentException e)
+        {
+            throw e;
+        }
+        catch (Throwable e)
+        {
+            logger.error("Failed to stop Async-Profiler", e);
+            return false;
+        }
+    }
+
+    public String execute(String command)
+    {
+        try
+        {
+            String result = 
maybeInitialize().execute(validateCommand(command));
+            logger.debug("Executed raw command in Async-Profiler: result={}, 
cmd={}", result, command);
+            return result;
+        }
+        catch (Throwable e)
+        {
+            logger.error("Failed to execute raw Async-Profiler command {}", 
command, e);
+            throw new RuntimeException(e);
+        }
+    }
+
+    public List<String> list()
+    {
+        try
+        {
+            createLogDir();

Review Comment:
   I think there's no harm there?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to