diff --git a/ddprof-lib/src/main/cpp/arguments.cpp b/ddprof-lib/src/main/cpp/arguments.cpp index f0e859defe..08649872fc 100644 --- a/ddprof-lib/src/main/cpp/arguments.cpp +++ b/ddprof-lib/src/main/cpp/arguments.cpp @@ -318,6 +318,17 @@ Error Arguments::parse(const char *args) { _lightweight = false; } } + CASE("wallsampler") + if (value != NULL) { + switch (value[0]) { + case 'j': + _wallclock_sampler = JVMTI; + break; + case 'a': + default: + _wallclock_sampler = ASGCT; + } + } DEFAULT() if (_unknown_arg == NULL) diff --git a/ddprof-lib/src/main/cpp/arguments.h b/ddprof-lib/src/main/cpp/arguments.h index 28c098e66b..45d87271cd 100644 --- a/ddprof-lib/src/main/cpp/arguments.h +++ b/ddprof-lib/src/main/cpp/arguments.h @@ -81,6 +81,11 @@ enum JfrOption { NO_SYSTEM_INFO | NO_SYSTEM_PROPS | NO_NATIVE_LIBS | NO_CPU_LOAD }; +enum WallclockSampler { + ASGCT, + JVMTI +}; + struct Multiplier { char symbol; long multiplier; @@ -123,37 +128,55 @@ class Arguments { long _wall; bool _wall_collapsing; int _wall_threads_per_tick; + WallclockSampler _wallclock_sampler; long _memory; bool _record_allocations; bool _record_liveness; double _live_samples_ratio; bool _record_heap_usage; bool _gc_generations; - int _jstackdepth; + int _jstackdepth; int _safe_mode; - const char *_file; - const char *_log; - const char *_loglevel; - const char *_unknown_arg; - const char *_filter; + const char* _file; + const char* _log; + const char* _loglevel; + const char* _unknown_arg; + const char* _filter; CStack _cstack; int _jfr_options; std::vector _context_attributes; bool _lightweight; Arguments(bool persistent = false) - : _buf(NULL), _shared(false), _persistent(persistent), - _action(ACTION_NONE), _ring(RING_ANY), _event(NULL), _interval(0), - _cpu(-1), _wall(-1), _wall_collapsing(false), - _wall_threads_per_tick(DEFAULT_WALL_THREADS_PER_TICK), _memory(-1), - _record_allocations(false), _record_liveness(false), - _live_samples_ratio( - 0.1), // default to liveness-tracking 10% of the allocation samples - _record_heap_usage(false), _gc_generations(false), - _jstackdepth(DEFAULT_JSTACKDEPTH), _safe_mode(0), _file(NULL), - _log(NULL), _loglevel(NULL), _unknown_arg(NULL), _filter(NULL), - _cstack(CSTACK_DEFAULT), _jfr_options(0), _context_attributes({}), - _lightweight(false) {} + : _buf(NULL), + _shared(false), + _persistent(persistent), + _action(ACTION_NONE), + _ring(RING_ANY), + _event(NULL), + _interval(0), + _cpu(-1), + _wall(-1), + _wall_collapsing(false), + _wall_threads_per_tick(DEFAULT_WALL_THREADS_PER_TICK), + _memory(-1), + _record_allocations(false), + _record_liveness(false), + _live_samples_ratio(0.1), // default to liveness-tracking 10% of the allocation samples + _record_heap_usage(false), + _gc_generations(false), + _jstackdepth(DEFAULT_JSTACKDEPTH), + _safe_mode(0), + _file(NULL), + _log(NULL), + _loglevel(NULL), + _unknown_arg(NULL), + _filter(NULL), + _cstack(CSTACK_DEFAULT), + _jfr_options(0), + _context_attributes({}), + _lightweight(false), + _wallclock_sampler(ASGCT) {} ~Arguments(); diff --git a/ddprof-lib/src/main/cpp/callTraceStorage.cpp b/ddprof-lib/src/main/cpp/callTraceStorage.cpp index 78e3535768..7850623d34 100644 --- a/ddprof-lib/src/main/cpp/callTraceStorage.cpp +++ b/ddprof-lib/src/main/cpp/callTraceStorage.cpp @@ -203,7 +203,7 @@ CallTrace *CallTraceStorage::findCallTrace(LongHashTable *table, u64 hash) { } u32 CallTraceStorage::put(int num_frames, ASGCT_CallFrame *frames, - bool truncated, u64 counter) { + bool truncated, u64 weight) { // Currently, CallTraceStorage is a singleton used globally in Profiler and // therefore start-stop operation requires data structures cleanup. This // cleanup may and will race this method and the racing can cause all sorts of @@ -268,7 +268,7 @@ u32 CallTraceStorage::put(int num_frames, ASGCT_CallFrame *frames, CallTraceSample &s = table->values()[slot]; atomicInc(s.samples); - atomicInc(s.counter, counter); + atomicInc(s.counter, weight); _lock.unlockShared(); return capacity - (INITIAL_CAPACITY - 1) + slot; diff --git a/ddprof-lib/src/main/cpp/callTraceStorage.h b/ddprof-lib/src/main/cpp/callTraceStorage.h index 72329f4582..c24f2be556 100644 --- a/ddprof-lib/src/main/cpp/callTraceStorage.h +++ b/ddprof-lib/src/main/cpp/callTraceStorage.h @@ -79,7 +79,7 @@ class CallTraceStorage { void clear(); void collectTraces(std::map &map); - u32 put(int num_frames, ASGCT_CallFrame *frames, bool truncated, u64 counter); + u32 put(int num_frames, ASGCT_CallFrame *frames, bool truncated, u64 weight); }; #endif // _CALLTRACESTORAGE diff --git a/ddprof-lib/src/main/cpp/flightRecorder.cpp b/ddprof-lib/src/main/cpp/flightRecorder.cpp index 5367fb5f1c..23448ba610 100644 --- a/ddprof-lib/src/main/cpp/flightRecorder.cpp +++ b/ddprof-lib/src/main/cpp/flightRecorder.cpp @@ -1550,7 +1550,7 @@ void FlightRecorder::recordHeapUsage(int lock_index, long value, bool live) { } void FlightRecorder::recordEvent(int lock_index, int tid, u32 call_trace_id, - int event_type, Event *event, u64 counter) { + int event_type, Event *event) { if (_rec != NULL) { RecordingBuffer *buf = _rec->buffer(lock_index); switch (event_type) { diff --git a/ddprof-lib/src/main/cpp/flightRecorder.h b/ddprof-lib/src/main/cpp/flightRecorder.h index 13feaec1a8..ec9dd2fc0b 100644 --- a/ddprof-lib/src/main/cpp/flightRecorder.h +++ b/ddprof-lib/src/main/cpp/flightRecorder.h @@ -309,7 +309,7 @@ class FlightRecorder { bool active() const { return _rec != NULL; } void recordEvent(int lock_index, int tid, u32 call_trace_id, int event_type, - Event *event, u64 counter); + Event *event); void recordLog(LogLevel level, const char *message, size_t len); diff --git a/ddprof-lib/src/main/cpp/profiler.cpp b/ddprof-lib/src/main/cpp/profiler.cpp index fb93fa5769..45e3320fff 100644 --- a/ddprof-lib/src/main/cpp/profiler.cpp +++ b/ddprof-lib/src/main/cpp/profiler.cpp @@ -57,7 +57,8 @@ static void (*orig_busHandler)(int signo, siginfo_t *siginfo, void *ucontext); static Engine noop_engine; static PerfEvents perf_events; -static WallClock wall_engine; +static WallClockASGCT wall_asgct_engine; +static WallClockJVMTI wall_jvmti_engine; static J9WallClock j9_engine; static ITimer itimer; static CTimer ctimer; @@ -690,7 +691,7 @@ void Profiler::recordExternalSample(u64 counter, int tid, call_trace_id = _call_trace_storage.put(num_frames, frames, truncated, counter); } - _jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event, counter); + _jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event); _locks[lock_index].unlock(); } @@ -763,7 +764,7 @@ void Profiler::recordSample(void *ucontext, u64 counter, int tid, thread->recordCallTraceId(call_trace_id); } } - _jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event, counter); + _jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event); _locks[lock_index].unlock(); } @@ -801,13 +802,13 @@ void Profiler::recordQueueTime(int tid, QueueTimeEvent *event) { _locks[lock_index].unlock(); } -void Profiler::recordExternalSample(u64 counter, int tid, int num_frames, +void Profiler::recordExternalSample(u64 weight, int tid, int num_frames, ASGCT_CallFrame *frames, bool truncated, jint event_type, Event *event) { atomicInc(_total_samples); u32 call_trace_id = - _call_trace_storage.put(num_frames, frames, truncated, counter); + _call_trace_storage.put(num_frames, frames, truncated, weight); u32 lock_index = getLockIndex(tid); if (!_locks[lock_index].tryLock() && @@ -818,7 +819,7 @@ void Profiler::recordExternalSample(u64 counter, int tid, int num_frames, return; } - _jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event, counter); + _jfr.recordEvent(lock_index, tid, call_trace_id, event_type, event); _locks[lock_index].unlock(); } @@ -1064,7 +1065,13 @@ Engine *Profiler::selectWallEngine(Arguments &args) { "wallclock profiler on your own risk."); } } - return (Engine *)&wall_engine; + switch (args._wallclock_sampler) { + case JVMTI: + return (Engine*)&wall_jvmti_engine; + case ASGCT: + default: + return (Engine*)&wall_asgct_engine; + } } Engine *Profiler::selectAllocEngine(Arguments &args) { diff --git a/ddprof-lib/src/main/cpp/profiler.h b/ddprof-lib/src/main/cpp/profiler.h index 230524c5ec..9806e748bb 100644 --- a/ddprof-lib/src/main/cpp/profiler.h +++ b/ddprof-lib/src/main/cpp/profiler.h @@ -214,12 +214,12 @@ class Profiler { void switchThreadEvents(jvmtiEventMode mode); int convertNativeTrace(int native_frames, const void **callchain, ASGCT_CallFrame *frames); - void recordSample(void *ucontext, u64 counter, int tid, jint event_type, + void recordSample(void *ucontext, u64 weight, int tid, jint event_type, u32 call_trace_id, Event *event); - void recordExternalSample(u64 counter, int tid, jvmtiFrameInfo *jvmti_frames, + void recordExternalSample(u64 weight, int tid, jvmtiFrameInfo *jvmti_frames, jint num_jvmti_frames, bool truncated, jint event_type, Event *event); - void recordExternalSample(u64 counter, int tid, int num_frames, + void recordExternalSample(u64 weight, int tid, int num_frames, ASGCT_CallFrame *frames, bool truncated, jint event_type, Event *event); void recordWallClockEpoch(int tid, WallClockEpochEvent *event); diff --git a/ddprof-lib/src/main/cpp/reservoirSampler.h b/ddprof-lib/src/main/cpp/reservoirSampler.h new file mode 100644 index 0000000000..8a91757b51 --- /dev/null +++ b/ddprof-lib/src/main/cpp/reservoirSampler.h @@ -0,0 +1,63 @@ +/* + * Copyright 2024 Datadog + * + * Licensed 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. + */ + +#ifndef RESERVOIR_SAMPLER_H +#define RESERVOIR_SAMPLER_H + +#include +#include +#include + + +template +class ReservoirSampler { +private: + const int size; + std::mt19937 generator; + std::uniform_real_distribution uniform; + std::uniform_int_distribution random_index; + std::vector reservoir; + +public: + ReservoirSampler(const int size) : + size(size), + generator([]() { + std::random_device rd; + std::seed_seq seed_seq{rd(), rd(), rd(), rd()}; + return std::mt19937(seed_seq); + }()), + uniform(1e-16, 1.0), + random_index(0, size - 1) { + reservoir.reserve(size); + } + + std::vector& sample(const std::vector &input) { + reservoir.clear(); + for (int i = 0; i < size && i < input.size(); i++) { + reservoir.push_back(input[i]); + } + double weight = exp(log(uniform(generator)) / size); + int target = size + (int) (log(uniform(generator)) / log(1 - weight)); + while (target < input.size()) { + reservoir[random_index(generator)] = input[target]; + weight *= exp(log(uniform(generator)) / size); + target += (int) (log(uniform(generator)) / log(1 - weight)); + } + return reservoir; + } +}; + +#endif //RESERVOIR_SAMPLER_H \ No newline at end of file diff --git a/ddprof-lib/src/main/cpp/vmStructs.h b/ddprof-lib/src/main/cpp/vmStructs.h index ac771a7f00..206bcb01f4 100644 --- a/ddprof-lib/src/main/cpp/vmStructs.h +++ b/ddprof-lib/src/main/cpp/vmStructs.h @@ -394,6 +394,22 @@ class NMethod : VMStructs { int findScopeOffset(const void *pc); }; +// Copied from JDK's globalDefinitions.hpp 'JavaThreadState' enum +enum JVMJavaThreadState { + _thread_uninitialized = 0, // should never happen (missing initialization) + _thread_new = 2, // just starting up, i.e., in process of being initialized + _thread_new_trans = 3, // corresponding transition state (not used, included for completeness) + _thread_in_native = 4, // running in native code + _thread_in_native_trans = 5, // corresponding transition state + _thread_in_vm = 6, // running in VM + _thread_in_vm_trans = 7, // corresponding transition state + _thread_in_Java = 8, // running in Java or in stub code + _thread_in_Java_trans = 9, // corresponding transition state (not used, included for completeness) + _thread_blocked = 10, // blocked in vm + _thread_blocked_trans = 11, // corresponding transition state + _thread_max_state = 12 // maximum thread state+1 - used for statistics allocation +}; + class VMThread : VMStructs { public: static VMThread *current(); diff --git a/ddprof-lib/src/main/cpp/wallClock.cpp b/ddprof-lib/src/main/cpp/wallClock.cpp index 6ec9c1c183..8525fea0f0 100644 --- a/ddprof-lib/src/main/cpp/wallClock.cpp +++ b/ddprof-lib/src/main/cpp/wallClock.cpp @@ -15,20 +15,20 @@ */ #include "wallClock.h" +#include "stackFrame.h" #include "context.h" #include "debugSupport.h" #include "log.h" #include "profiler.h" #include "stackFrame.h" #include "thread.h" -#include "tsc.h" #include "vmStructs.h" #include #include -std::atomic WallClock::_enabled{false}; +std::atomic BaseWallClock::_enabled{false}; -bool WallClock::inSyscall(void *ucontext) { +bool WallClockASGCT::inSyscall(void *ucontext) { StackFrame frame(ucontext); uintptr_t pc = frame.pc(); @@ -53,15 +53,15 @@ bool WallClock::inSyscall(void *ucontext) { return false; } -void WallClock::sharedSignalHandler(int signo, siginfo_t *siginfo, +void WallClockASGCT::sharedSignalHandler(int signo, siginfo_t *siginfo, void *ucontext) { - WallClock *engine = (WallClock *)Profiler::instance()->wallEngine(); + WallClockASGCT *engine = reinterpret_cast(Profiler::instance()->wallEngine()); if (signo == SIGVTALRM) { engine->signalHandler(signo, siginfo, ucontext, engine->_interval); } } -void WallClock::signalHandler(int signo, siginfo_t *siginfo, void *ucontext, +void WallClockASGCT::signalHandler(int signo, siginfo_t *siginfo, void *ucontext, u64 last_sample) { ProfiledThread *current = ProfiledThread::current(); int tid = current != NULL ? current->tid() : OS::threadId(); @@ -109,19 +109,19 @@ void WallClock::signalHandler(int signo, siginfo_t *siginfo, void *ucontext, Shims::instance().setSighandlerTid(-1); } -Error WallClock::start(Arguments &args) { +Error BaseWallClock::start(Arguments &args) { int interval = args._event != NULL ? args._interval : args._wall; if (interval < 0) { return Error("interval must be positive"); } _interval = interval ? interval : DEFAULT_WALL_INTERVAL; - _collapsing = args._wall_collapsing; - - _reservoir_size = args._wall_threads_per_tick ? args._wall_threads_per_tick + _reservoir_size = + args._wall_threads_per_tick ? + args._wall_threads_per_tick : DEFAULT_WALL_THREADS_PER_TICK; - OS::installSignalHandler(SIGVTALRM, sharedSignalHandler); + initialize(args); _running = true; @@ -132,7 +132,7 @@ Error WallClock::start(Arguments &args) { return Error::OK; } -void WallClock::stop() { +void BaseWallClock::stop() { _running.store(false); // the thread join ensures we wait for the thread to finish before returning // (and possibly removing the object) @@ -143,90 +143,129 @@ void WallClock::stop() { } } -void WallClock::timerLoop() { - if (!_enabled.load(std::memory_order_acquire)) { +bool BaseWallClock::isEnabled() const { + return _enabled.load(std::memory_order_acquire); +} + +void WallClockASGCT::initialize(Arguments& args) { + _collapsing = args._wall_collapsing; + OS::installSignalHandler(SIGVTALRM, sharedSignalHandler); +} + +void WallClockJVMTI::timerLoop() { + // Check for enablement before attaching/dettaching the current thread + if (!isEnabled()) { return; } - std::vector tids; - tids.reserve(_reservoir_size); - std::vector reservoir; - reservoir.reserve(_reservoir_size); - int self = OS::threadId(); - ThreadFilter *thread_filter = Profiler::instance()->threadFilter(); - thread_filter->remove(self); - - std::mt19937 generator(std::random_device{}()); - std::uniform_real_distribution uniform(1e-16, 1.0); - std::uniform_int_distribution random_index(0, _reservoir_size - 1); - - u64 startTime = TSC::ticks(); - WallClockEpochEvent epoch(startTime); - - while (_running.load(std::memory_order_relaxed)) { - if (thread_filter->enabled()) { - thread_filter->collect(tids); + // Attach to JVM as the first step + VM::attachThread("Datadog Profiler Wallclock Sampler"); + auto collectThreads = [&](std::vector& threads) { + jvmtiEnv* jvmti = VM::jvmti(); + if (jvmti == nullptr) { + return; + } + JNIEnv* jni = VM::jni(); + + jint threads_count = 0; + jthread* threads_ptr = nullptr; + jvmti->GetAllThreads(&threads_count, &threads_ptr); + + bool do_filter = Profiler::instance()->threadFilter()->enabled(); + int self = OS::threadId(); + + for (int i = 0; i < threads_count; i++) { + jthread thread = threads_ptr[i]; + if (thread != nullptr) { + VMThread* nThread = VMThread::fromJavaThread(jni, thread); + if (nThread == nullptr) { + continue; + } + int tid = nThread->osThreadId(); + if (tid != self && (!do_filter || Profiler::instance()->threadFilter()->accept(tid))) { + threads.push_back({nThread, thread}); + } + } + } + jvmti->Deallocate((unsigned char*)threads_ptr); + }; + + auto sampleThreads = [&](ThreadEntry& thread_entry, int& num_failures, int& threads_already_exited, int& permission_denied) { + jint max_stack_depth = (jint)Profiler::instance()->max_stack_depth(); + jvmtiFrameInfo* frame_buffer = new jvmtiFrameInfo[max_stack_depth]; + jvmtiEnv* jvmti = VM::jvmti(); + + int num_frames = 0; + jvmtiError err = jvmti->GetStackTrace(thread_entry.java, 0, max_stack_depth, frame_buffer, &num_frames); + if (err != JVMTI_ERROR_NONE) { + num_failures++; + if (err == JVMTI_ERROR_THREAD_NOT_ALIVE) { + threads_already_exited++; + } + return false; + } + ExecutionEvent event; + VMThread* vm_thread = thread_entry.native; + int raw_thread_state = vm_thread->state(); + bool is_initialized = raw_thread_state >= JVMJavaThreadState::_thread_in_native && + raw_thread_state < JVMJavaThreadState::_thread_max_state; + ThreadState state = ThreadState::UNKNOWN; + ExecutionMode mode = ExecutionMode::UNKNOWN; + if (vm_thread && is_initialized) { + ThreadState os_state = vm_thread->osThreadState(); + if (os_state != ThreadState::UNKNOWN) { + state = os_state; + } + mode = convertJvmExecutionState(raw_thread_state); + } + if (state == ThreadState::UNKNOWN) { + state = ThreadState::RUNNABLE; + } + event._thread_state = state; + event._execution_mode = mode; + event._weight = 1; + + Profiler::instance()->recordExternalSample(1, thread_entry.native->osThreadId(), frame_buffer, num_frames, false, BCI_WALL, &event); + return true; + }; + + timerLoopCommon(collectThreads, sampleThreads, _reservoir_size, _interval); + // Don't forget to detach the thread + VM::detachThread(); +} + +void WallClockASGCT::timerLoop() { + auto collectThreads = [&](std::vector& tids) { + if (Profiler::instance()->threadFilter()->enabled()) { + Profiler::instance()->threadFilter()->collect(tids); } else { ThreadList *thread_list = OS::listThreads(); int tid = thread_list->next(); while (tid != -1) { - if (tid != self) { - tids.push_back(tid); - } - tid = thread_list->next(); - } - delete thread_list; - } - for (int i = 0; i < _reservoir_size && i < tids.size(); i++) { - reservoir.push_back(tids[i]); - } - double weight = exp(log(uniform(generator)) / _reservoir_size); - int target = - _reservoir_size + (int)(log(uniform(generator)) / log(1 - weight)); - while (target < tids.size()) { - reservoir[random_index(generator)] = tids[target]; - weight *= exp(log(uniform(generator)) / _reservoir_size); - target += (int)(log(uniform(generator)) / log(1 - weight)); - } - - int num_failures = 0; - int threads_already_exited = 0; - int permission_denied = 0; - for (int tid : reservoir) { - if (!OS::sendSignalToThread(tid, SIGVTALRM)) { - num_failures++; - if (errno != 0) { - switch (errno) { - case ESRCH: - threads_already_exited++; - break; - case EPERM: - permission_denied++; - break; - default: - Log::debug("unexpected error %s", strerror(errno)); - } + if (tid != OS::threadId()) { + tids.push_back(tid); + } + tid = thread_list->next(); + } + delete thread_list; } - } - } + }; - epoch.updateNumSamplableThreads(tids.size()); - epoch.updateNumFailedSamples(num_failures); - epoch.updateNumSuccessfulSamples(reservoir.size() - num_failures); - epoch.updateNumExitedThreads(threads_already_exited); - epoch.updateNumPermissionDenied(permission_denied); - u64 endTime = TSC::ticks(); - u64 duration = TSC::ticks_to_millis(endTime - startTime); - if (epoch.hasChanged() || duration >= 1000) { - epoch.endEpoch(duration); - Profiler::instance()->recordWallClockEpoch(self, &epoch); - epoch.newEpoch(endTime); - startTime = endTime; - } else { - epoch.clean(); + auto sampleThreads = [&](int tid, int& num_failures, int& threads_already_exited, int& permission_denied) { + if (!OS::sendSignalToThread(tid, SIGVTALRM)) { + num_failures++; + if (errno != 0) { + if (errno == ESRCH) { + threads_already_exited++; + } else if (errno == EPERM) { + permission_denied++; + } else { + Log::debug("unexpected error %s", strerror(errno)); + } + } + return false; } + return true; + }; - reservoir.clear(); - tids.clear(); - OS::sleep(_interval); - } + timerLoopCommon(collectThreads, sampleThreads, _reservoir_size, _interval); } diff --git a/ddprof-lib/src/main/cpp/wallClock.h b/ddprof-lib/src/main/cpp/wallClock.h index 55ec96cd04..4fa168e040 100644 --- a/ddprof-lib/src/main/cpp/wallClock.h +++ b/ddprof-lib/src/main/cpp/wallClock.h @@ -19,59 +19,152 @@ #include "engine.h" #include "os.h" +#include "profiler.h" +#include "reservoirSampler.h" +#include "threadFilter.h" #include "threadState.h" -#include -#include -#include -#include - -class WallClock : public Engine { -private: - static std::atomic _enabled; - - bool _collapsing; - long _interval; - - // Maximum number of threads sampled in one iteration. This limit serves as a +#include "tsc.h" +#include "vmStructs.h" + +class BaseWallClock : public Engine { + private: + static std::atomic _enabled; + std::atomic _running; + protected: + long _interval; + // Maximum number of threads sampled in one iteration. This limit serves as a // throttle when generating profiling signals. Otherwise applications with too // many threads may suffer from a big profiling overhead. Also, keeping this // limit low enough helps to avoid contention on a spin lock inside // Profiler::recordSample(). int _reservoir_size; - std::atomic _running; - pthread_t _thread; - - void timerLoop(); + pthread_t _thread; + virtual void timerLoop() = 0; + virtual void initialize(Arguments& args) {}; static void *threadEntry(void *wall_clock) { - ((WallClock *)wall_clock)->timerLoop(); + ((BaseWallClock *)wall_clock)->timerLoop(); return NULL; } - static bool inSyscall(void *ucontext); - - static void sharedSignalHandler(int signo, siginfo_t *siginfo, - void *ucontext); - void signalHandler(int signo, siginfo_t *siginfo, void *ucontext, - u64 last_sample); + bool isEnabled() const; + + template + void timerLoopCommon(CollectThreadsFunc collectThreads, SampleThreadsFunc sampleThreads, int reservoirSize, u64 interval) { + if (!_enabled.load(std::memory_order_acquire)) { + return; + } + + // Dither the sampling interval to introduce some randomness and prevent step-locking + const double stddev = ((double)_interval) / 10.0; // 10% standard deviation + // Set up random engine and normal distribution + std::random_device rd; + std::mt19937 generator(rd()); + std::normal_distribution distribution(interval, stddev); + + std::vector threads; + threads.reserve(reservoirSize); + int self = OS::threadId(); + ThreadFilter* thread_filter = Profiler::instance()->threadFilter(); + thread_filter->remove(self); + + u64 startTime = TSC::ticks(); + WallClockEpochEvent epoch(startTime); + + ReservoirSampler reservoir(reservoirSize); + + while (_running.load(std::memory_order_relaxed)) { + collectThreads(threads); + + int num_failures = 0; + int threads_already_exited = 0; + int permission_denied = 0; + std::vector sample = reservoir.sample(threads); + for (ThreadType thread : sample) { + if (!sampleThreads(thread, num_failures, threads_already_exited, permission_denied)) { + continue; + } + } + + epoch.updateNumSamplableThreads(threads.size()); + epoch.updateNumFailedSamples(num_failures); + epoch.updateNumSuccessfulSamples(sample.size() - num_failures); + epoch.updateNumExitedThreads(threads_already_exited); + epoch.updateNumPermissionDenied(permission_denied); + u64 endTime = TSC::ticks(); + u64 duration = TSC::ticks_to_millis(endTime - startTime); + if (epoch.hasChanged() || duration >= 1000) { + epoch.endEpoch(duration); + Profiler::instance()->recordWallClockEpoch(self, &epoch); + epoch.newEpoch(endTime); + startTime = endTime; + } else { + epoch.clean(); + } + + threads.clear(); + // Get a random sleep duration + // clamp the random interval to <1,2N-1> + // the probability of clamping is extremely small, close to zero + OS::sleep(std::min(std::max((long int)1, static_cast(distribution(generator))), ((_interval * 2) - 1))); + } + } public: - WallClock() - : _collapsing(false), _interval(LONG_MAX), _reservoir_size(0), - _running(false), _thread(0) {} + BaseWallClock() : + _interval(LONG_MAX), + _reservoir_size(0), + _running(false), + _thread(0) {} + virtual ~BaseWallClock() = default; - const char *units() { return "ns"; } + const char* units() { + return "ns"; + } - const char *name() { return "WallClock"; } + virtual const char* name() = 0; long interval() const { return _interval; } - Error start(Arguments &args); - void stop(); - inline void enableEvents(bool enabled) { - _enabled.store(enabled, std::memory_order_release); + _enabled.store(enabled, std::memory_order_release); + } + + Error start(Arguments& args); + void stop(); +}; + +class WallClockASGCT : public BaseWallClock { + private: + bool _collapsing; + + static bool inSyscall(void* ucontext); + + static void sharedSignalHandler(int signo, siginfo_t* siginfo, void* ucontext); + void signalHandler(int signo, siginfo_t* siginfo, void* ucontext, u64 last_sample); + + void initialize(Arguments& args) override; + void timerLoop() override; + + public: + WallClockASGCT() : BaseWallClock(), _collapsing(false) {} + const char* name() override { + return "WallClock (ASGCT)"; + } +}; + +class WallClockJVMTI : public BaseWallClock { + private: + void timerLoop() override; + public: + struct ThreadEntry { + VMThread* native; + jthread java; + }; + WallClockJVMTI() : BaseWallClock() {} + const char* name() override { + return "WallClock (JVMTI)"; } }; diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/ContendedWallclockSamplesTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/ContendedWallclockSamplesTest.java index f4123ba36c..35bc9d8189 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/ContendedWallclockSamplesTest.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/ContendedWallclockSamplesTest.java @@ -4,7 +4,6 @@ import com.datadoghq.profiler.Platform; import com.datadoghq.profiler.context.ContextExecutor; import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.Test; import org.junitpioneer.jupiter.RetryingTest; import org.openjdk.jmc.common.item.IItem; import org.openjdk.jmc.common.item.IItemIterable; diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/JvmtiBasedContextWallClockTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/JvmtiBasedContextWallClockTest.java new file mode 100644 index 0000000000..2c4a67779f --- /dev/null +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/JvmtiBasedContextWallClockTest.java @@ -0,0 +1,9 @@ +package com.datadoghq.profiler.wallclock; + +public class JvmtiBasedContextWallClockTest extends ContextWallClockTest { + + @Override + protected String getProfilerCommand() { + return super.getProfilerCommand() + ";wallsampler=jvmti"; + } +} \ No newline at end of file diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/JvmtiBasedWallClockThreadFilterTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/JvmtiBasedWallClockThreadFilterTest.java new file mode 100644 index 0000000000..f92a1e5ae6 --- /dev/null +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/JvmtiBasedWallClockThreadFilterTest.java @@ -0,0 +1,9 @@ +package com.datadoghq.profiler.wallclock; + +public class JvmtiBasedWallClockThreadFilterTest extends WallClockThreadFilterTest { + + @Override + protected String getProfilerCommand() { + return super.getProfilerCommand() + ";wallsampler=jvmti"; + } +} \ No newline at end of file diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/MegamorphicCallTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/MegamorphicCallTest.java index dfa1b9996c..50b29b3783 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/MegamorphicCallTest.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/MegamorphicCallTest.java @@ -3,7 +3,6 @@ import com.datadoghq.profiler.AbstractProfilerTest; import com.datadoghq.profiler.Platform; import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.Test; import org.junitpioneer.jupiter.RetryingTest; import org.openjdk.jmc.common.item.IItem; import org.openjdk.jmc.common.item.IItemCollection; diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/WallclockThreadFilterTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/WallClockThreadFilterTest.java similarity index 96% rename from ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/WallclockThreadFilterTest.java rename to ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/WallClockThreadFilterTest.java index 9004d550f3..de2de82f6b 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/WallclockThreadFilterTest.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/wallclock/WallClockThreadFilterTest.java @@ -13,7 +13,7 @@ import com.datadoghq.profiler.AbstractProfilerTest; import com.datadoghq.profiler.Platform; -public class WallclockThreadFilterTest extends AbstractProfilerTest { +public class WallClockThreadFilterTest extends AbstractProfilerTest { @Test public void test() throws InterruptedException {