Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-23 10:34:42

0001 
0002 #include "JExecutionEngine.h"
0003 #include "JANA/Utils/JEventLevel.h"
0004 #include "JANA/Utils/JTypeInfo.h"
0005 #include <JANA/Utils/JApplicationInspector.h>
0006 #include <JANA/JVersion.h>
0007 
0008 #if JANA2_HAVE_PERFETTO
0009 #include <JANA/Services/JPerfettoService.h>
0010 #endif
0011 
0012 #include <chrono>
0013 #include <cstddef>
0014 #include <cstdio>
0015 #include <ctime>
0016 #include <exception>
0017 #include <mutex>
0018 #include <csignal>
0019 #include <ostream>
0020 #include <sstream>
0021 #include <sys/stat.h>
0022 #include <fcntl.h>
0023 #include <unistd.h>
0024 
0025 thread_local int jana2_worker_id = -1;
0026 thread_local JBacktrace* jana2_worker_backtrace = nullptr;
0027 
0028 void JExecutionEngine::Init() {
0029     auto params = GetApplication()->GetJParameterManager();
0030 
0031     params->SetDefaultParameter("jana:timeout", m_timeout_s, 
0032         "Max time (in seconds) JANA will wait for a thread to update its heartbeat before hard-exiting. 0 to disable timeout completely.");
0033 
0034     params->SetDefaultParameter("jana:warmup_timeout", m_warmup_timeout_s, 
0035         "Max time (in seconds) JANA will wait for 'initial' events to complete before hard-exiting.");
0036 
0037     params->SetDefaultParameter("jana:backoff_interval", m_backoff_ms, 
0038         "Max time (in seconds) JANA will wait for 'initial' events to complete before hard-exiting.");
0039 
0040     params->SetDefaultParameter("jana:show_ticker", m_show_ticker, "Controls whether the ticker is visible");
0041 
0042     params->SetDefaultParameter("jana:ticker_interval", m_ticker_ms, "Controls the ticker interval (in ms)");
0043 
0044     params->SetDefaultParameter("jana:ticker_level", m_ticker_level, "Controls the ticker event level (e.g. PhysicsEvent, Timeframe, Block, ...)");
0045 
0046     auto p = params->SetDefaultParameter("jana:status_fname", m_path_to_named_pipe,
0047         "Filename of named pipe for retrieving instantaneous status info");
0048 
0049     size_t pid = getpid();
0050     mkfifo(m_path_to_named_pipe.c_str(), 0666);
0051 
0052     LOG_WARN(GetLogger()) << "To pause processing and inspect, press Ctrl-C." << LOG_END;
0053     LOG_WARN(GetLogger()) << "For a clean shutdown, press Ctrl-C twice." << LOG_END;
0054     LOG_WARN(GetLogger()) << "For a hard shutdown, press Ctrl-C three times." << LOG_END;
0055 
0056     if (p->IsDefault()) {
0057         LOG_WARN(GetLogger()) << "For worker status information, press Ctrl-Z, or run `jana-status " << pid << "`" << LOG_END;
0058     }
0059     else {
0060         LOG_WARN(GetLogger()) << "For worker status information, press Ctrl-Z, or run `jana-status " << pid << " " << m_path_to_named_pipe << "`" << LOG_END;
0061     }
0062 
0063 
0064     // Not sure how I feel about putting this here yet, but I think it will at least work in both cases it needs to.
0065     // The reason this works is because JTopologyBuilder::create_topology() has already been called before 
0066     // JApplication::ProvideService<JExecutionEngine>().
0067     for (JArrow* arrow : m_topology->GetArrows()) {
0068 
0069         arrow->Initialize();
0070 
0071         m_arrow_states.emplace_back();
0072         auto& arrow_state = m_arrow_states.back();
0073         arrow_state.is_source = arrow->IsSource();
0074         arrow_state.is_parallel = arrow->IsParallel();
0075         arrow_state.next_input = arrow->GetNextPortIndex();
0076     }
0077 }
0078 
0079 void JExecutionEngine::RequestInspector() {
0080     std::unique_lock<std::mutex> lock(m_mutex);
0081     m_interrupt_status = InterruptStatus::InspectRequested;
0082 }
0083 
0084 void JExecutionEngine::RunTopology() {
0085     std::unique_lock<std::mutex> lock(m_mutex);
0086 
0087     LOG_INFO(GetLogger()) << "Calling RunTopology";
0088     if (m_runstatus == RunStatus::Failed) {
0089         throw JException("Cannot switch topology runstatus to Running because it is already Failed");
0090     }
0091     if (m_runstatus == RunStatus::Finished) {
0092         throw JException("Cannot switch topology runstatus to Running because it is already Finished");
0093     }
0094     if (m_arrow_states.size() == 0) {
0095         throw JException("Cannot execute an empty topology! Hint: Have you provided an event source?");
0096     }
0097 
0098     // Set start time and event count
0099     m_time_at_start = clock_t::now();
0100     m_time_at_finish = m_time_at_start;
0101     m_total_idle_duration = clock_t::duration::zero();
0102     m_total_scheduler_duration = clock_t::duration::zero();
0103     for (auto& pair : m_processed_event_counts) {
0104         //event_count_at_start = event_count_at_finish;
0105         pair.second.first = pair.second.second;
0106     }
0107     for (auto& arrow_state : m_arrow_states) {
0108         // Reset all arrow event counts to 0 when topology starts up
0109         for (auto& evt_counts : arrow_state.processed_event_counts) {
0110             evt_counts.second = 0;
0111         }
0112         arrow_state.total_processing_duration = clock_t::duration::zero();
0113     }
0114 
0115     // Reactivate topology
0116     for (auto& arrow: m_arrow_states) {
0117         if (arrow.status == ArrowState::Status::Paused) {
0118             arrow.status = ArrowState::Status::Running;
0119         }
0120     }
0121 
0122     m_runstatus = RunStatus::Running;
0123 
0124     lock.unlock();
0125     m_condvar.notify_one();
0126 }
0127 
0128 void JExecutionEngine::ScaleWorkers(size_t nthreads) {
0129     // We both create and destroy the pool of workers here. They all sleep until they 
0130     // receive work from the scheduler, which won't happen until the runstatus <- {Running, 
0131     // Pausing, Draining} and there is a task ready to execute. This way worker creation/destruction
0132     // is decoupled from topology execution.
0133 
0134     // If we scale to zero, no workers will run. This is useful for testing, and also for using
0135     // an external thread team, should the need arise.
0136 
0137     std::unique_lock<std::mutex> lock(m_mutex);
0138 
0139     if (nthreads != 0 && m_arrow_states.size() == 0) {
0140         // We check that (nthreads != 0) because this gets called at shutdown even if the topology wasn't run
0141         // Remember, we want JApplication::Initialize() to succeed and JMain to shut down cleanly even when the topology is empty
0142         throw JException("Cannot execute an empty topology! Hint: Have you provided an event source?");
0143     }
0144 
0145     auto prev_nthreads = m_worker_states.size();
0146 
0147     if (prev_nthreads < nthreads) {
0148         // We are launching additional worker threads
0149         LOG_DEBUG(GetLogger()) << "Scaling up to " << nthreads << " worker threads" << LOG_END;
0150         auto mapping = m_topology->GetProcessorMapping();
0151         for (size_t worker_id=prev_nthreads; worker_id < nthreads; ++worker_id) {
0152             auto worker = std::make_unique<WorkerState>();
0153             worker->worker_id = worker_id;
0154             worker->is_stop_requested = false;
0155             worker->cpu_id = mapping.get_cpu_id(worker_id);
0156             worker->location_id = mapping.get_loc_id(worker_id);
0157             worker->thread = new std::thread(&JExecutionEngine::RunWorker, this, Worker{worker_id, &worker->backtrace});
0158             LOG_DEBUG(GetLogger()) << "Launching worker thread " << worker_id << " on cpu=" << worker->cpu_id << ", location=" << worker->location_id << LOG_END;
0159             m_worker_states.push_back(std::move(worker));
0160 
0161             bool pin_to_cpu = (mapping.get_affinity() != JProcessorMapping::AffinityStrategy::None);
0162             if (pin_to_cpu) {
0163                 JCpuInfo::PinThreadToCpu(worker->thread, worker->cpu_id);
0164             }
0165         }
0166     }
0167 
0168     else if (prev_nthreads > nthreads) {
0169         // We are destroying existing worker threads
0170         LOG_DEBUG(GetLogger()) << "Scaling down to " << nthreads << " worker threads" << LOG_END;
0171 
0172         // Signal to threads that they need to terminate.
0173         for (int worker_id=prev_nthreads-1; worker_id >= (int)nthreads; --worker_id) {
0174             LOG_DEBUG(GetLogger()) << "Stopping worker " << worker_id << LOG_END;
0175             m_worker_states[worker_id]->is_stop_requested = true;
0176         }
0177         m_condvar.notify_all(); // Wake up all threads so that they can exit the condvar wait loop
0178         lock.unlock();
0179 
0180         // We join all (eligible) threads _outside_ of the mutex
0181         for (int worker_id=prev_nthreads-1; worker_id >= (int) nthreads; --worker_id) {
0182             if (m_worker_states[worker_id]->thread != nullptr) {
0183                 if (m_worker_states[worker_id]->is_timed_out) {
0184                     // Thread has timed out. Rather than non-cooperatively killing it,
0185                     // we relinquish ownership of it but remember that it was ours once and
0186                     // is still out there, somewhere, biding its time
0187                     m_worker_states[worker_id]->thread->detach();
0188                     LOG_DEBUG(GetLogger()) << "Detached worker " << worker_id << LOG_END;
0189                 }
0190                 else {
0191                     LOG_DEBUG(GetLogger()) << "Joining worker " << worker_id << LOG_END;
0192                     m_worker_states[worker_id]->thread->join();
0193                     LOG_DEBUG(GetLogger()) << "Joined worker " << worker_id << LOG_END;
0194                 }
0195             }
0196             else {
0197                 LOG_DEBUG(GetLogger()) << "Skipping worker " << worker_id << LOG_END;
0198             }
0199         }
0200 
0201         lock.lock();
0202         // We retake the mutex so we can safely modify m_worker_states
0203         for (int worker_id=prev_nthreads-1; worker_id >= (int)nthreads; --worker_id) {
0204             if (m_worker_states.back()->thread != nullptr) {
0205                 delete m_worker_states.back()->thread;
0206             }
0207             m_worker_states.pop_back();
0208         }
0209     }
0210 }
0211 
0212 void JExecutionEngine::PauseTopology() {
0213     std::unique_lock<std::mutex> lock(m_mutex);
0214     if (m_runstatus != RunStatus::Running) return;
0215     m_runstatus = RunStatus::Pausing;
0216     for (auto& arrow: m_arrow_states) {
0217         if (arrow.status == ArrowState::Status::Running) {
0218             arrow.status = ArrowState::Status::Paused;
0219         }
0220     }
0221     LOG_WARN(GetLogger()) << "Requested pause" << LOG_END;
0222     lock.unlock();
0223     m_condvar.notify_all();
0224 }
0225 
0226 void JExecutionEngine::DrainTopology() {
0227     std::unique_lock<std::mutex> lock(m_mutex);
0228     if (m_runstatus != RunStatus::Running) return;
0229     m_runstatus = RunStatus::Draining;
0230     for (auto& arrow: m_arrow_states) {
0231         if (arrow.is_source) {
0232             if (arrow.status == ArrowState::Status::Running) {
0233                 arrow.status = ArrowState::Status::Paused;
0234             }
0235         }
0236     }
0237     LOG_WARN(GetLogger()) << "Requested drain" << LOG_END;
0238     lock.unlock();
0239     m_condvar.notify_all();
0240 }
0241 
0242 void JExecutionEngine::RunSupervisor() {
0243 
0244     if (m_interrupt_status == InterruptStatus::NoInterruptsUnsupervised) {
0245         m_interrupt_status = InterruptStatus::NoInterruptsSupervised;
0246     }
0247     size_t last_event_count = 0;
0248     clock_t::time_point last_measurement_time = clock_t::now();
0249 
0250     Perf perf;
0251     while (true) {
0252 
0253         if (m_enable_timeout && m_timeout_s > 0) {
0254             CheckTimeout();
0255         }
0256 
0257         if (m_print_worker_report_requested) {
0258             PrintWorkerReport(false);
0259             m_print_worker_report_requested = false;
0260         }
0261 
0262         if (m_send_worker_report_requested) {
0263             PrintWorkerReport(true);
0264             m_send_worker_report_requested = false;
0265         }
0266 
0267         perf = GetPerf();
0268         if ((perf.runstatus == RunStatus::Paused && m_interrupt_status != InterruptStatus::InspectRequested) || 
0269             perf.runstatus == RunStatus::Finished || 
0270             perf.runstatus == RunStatus::Failed) {
0271             break;
0272         }
0273 
0274         if (m_interrupt_status == InterruptStatus::InspectRequested) {
0275             if (perf.runstatus == RunStatus::Paused) {
0276                 PrintFinalReport();
0277                 LOG_INFO(GetLogger()) << "Entering inspector" << LOG_END;
0278                 m_enable_timeout = false;
0279                 m_interrupt_status = InterruptStatus::InspectInProgress;
0280                 InspectApplication(GetApplication());
0281                 m_interrupt_status = InterruptStatus::NoInterruptsSupervised;
0282 
0283                 // Jump back to the top of the loop so that we have fresh event count data
0284                 last_measurement_time = clock_t::now();
0285                 last_event_count = 0;
0286                 continue; 
0287             }
0288             else if (perf.runstatus == RunStatus::Running) {
0289                 PauseTopology();
0290             }
0291         }
0292         else if (m_interrupt_status == InterruptStatus::PauseAndQuit) {
0293             PauseTopology();
0294         }
0295 
0296         if (m_show_ticker) {
0297             auto next_event_count = perf.processed_event_counts[perf.event_level];
0298             auto next_measurement_time = clock_t::now();
0299             auto last_measurement_duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(next_measurement_time - last_measurement_time).count();
0300             float latest_throughput_hz = (last_measurement_duration_ms == 0) ? 0 : (next_event_count - last_event_count) * 1000.0 / last_measurement_duration_ms;
0301             last_measurement_time = next_measurement_time;
0302             last_event_count = next_event_count;
0303 
0304             // Print rates
0305             LOG_INFO(m_logger)
0306                 << "Status: " << next_event_count << " "
0307                 << ToStringWithLowercasePlurals(perf.event_level) << " processed at "
0308                 << JTypeInfo::to_string_with_si_prefix(latest_throughput_hz) << "Hz ("
0309                 << JTypeInfo::to_string_with_si_prefix(perf.throughputs_hz[perf.event_level]) << "Hz avg)" << LOG_END;
0310         }
0311 
0312         std::this_thread::sleep_for(std::chrono::milliseconds(m_ticker_ms));
0313     }
0314     LOG_INFO(GetLogger()) << "Processing paused." << LOG_END;
0315 
0316     if (perf.runstatus == RunStatus::Failed) {
0317         HandleFailures();
0318     }
0319 
0320     PrintFinalReport();
0321 }
0322 
0323 bool JExecutionEngine::CheckTimeout() {
0324     std::unique_lock<std::mutex> lock(m_mutex);
0325     auto now = clock_t::now();
0326     bool timeout_detected = false;
0327     for (auto& worker: m_worker_states) {
0328         auto timeout_s = (worker->is_event_warmed_up) ? m_timeout_s : m_warmup_timeout_s;
0329         auto duration_s = std::chrono::duration_cast<std::chrono::seconds>(now - worker->last_checkout_time).count();
0330         if (duration_s > timeout_s && worker->last_arrow_id != static_cast<uint64_t>(-1)) {
0331             worker->is_timed_out = true;
0332             timeout_detected = true;
0333             m_runstatus = RunStatus::Failed;
0334         }
0335     }
0336     return timeout_detected;
0337 }
0338 
0339 void JExecutionEngine::HandleFailures() {
0340 
0341     std::unique_lock<std::mutex> lock(m_mutex);
0342 
0343     // First, we log all of the failures we've found
0344     for (auto& worker: m_worker_states) {
0345         if (worker->is_timed_out) {
0346             std::string arrow_name = (worker->last_arrow_id == static_cast<uint64_t>(-1)) ? "(none)" : m_topology->GetArrows()[worker->last_arrow_id]->GetName();
0347             LOG_FATAL(GetLogger()) << "Timeout in worker thread " << worker->worker_id << " while executing " << arrow_name << " on event #" << worker->last_event_nr << LOG_END;
0348             pthread_kill(worker->thread->native_handle(), SIGUSR2);
0349             LOG_INFO(GetLogger()) << "Worker thread signalled; waiting for backtrace capture." << LOG_END;
0350             worker->backtrace.WaitForCapture();
0351         }
0352         if (worker->stored_exception != nullptr) {
0353             std::string arrow_name = (worker->last_arrow_id == static_cast<uint64_t>(-1)) ? "(none)" : m_topology->GetArrows()[worker->last_arrow_id]->GetName();
0354             LOG_FATAL(GetLogger()) << "Exception in worker thread " << worker->worker_id << " while executing " << arrow_name << " on event #" << worker->last_event_nr << LOG_END;
0355         }
0356     }
0357 
0358     // Now we throw each of these exceptions in order, in case the caller is going to attempt to catch them.
0359     // In reality all callers are going to print everything they can about the exception and exit.
0360     for (auto& worker: m_worker_states) {
0361         if (worker->stored_exception != nullptr) {
0362             GetApplication()->SetExitCode((int) JApplication::ExitCode::UnhandledException);
0363             std::rethrow_exception(worker->stored_exception);
0364         }
0365         if (worker->is_timed_out) {
0366             GetApplication()->SetExitCode((int) JApplication::ExitCode::Timeout);
0367             auto ex = JException("Timeout in worker thread");
0368             ex.backtrace = worker->backtrace;
0369             throw ex;
0370         }
0371     }
0372 }
0373 
0374 void JExecutionEngine::FinishTopology() {
0375     std::unique_lock<std::mutex> lock(m_mutex);
0376     assert(m_runstatus == RunStatus::Paused);
0377 
0378     LOG_DEBUG(GetLogger()) << "Finishing processing..." << LOG_END;
0379     for (auto* arrow : m_topology->GetArrows()) {
0380         arrow->Finalize();
0381     }
0382     for (auto* pool: m_topology->GetPools()) {
0383         pool->Finalize();
0384     }
0385     m_runstatus = RunStatus::Finished;
0386     LOG_INFO(GetLogger()) << "Finished processing." << LOG_END;
0387 }
0388 
0389 JExecutionEngine::RunStatus JExecutionEngine::GetRunStatus() {
0390     std::unique_lock<std::mutex> lock(m_mutex);
0391     return m_runstatus;
0392 }
0393 
0394 JExecutionEngine::Perf JExecutionEngine::GetPerf() {
0395     std::unique_lock<std::mutex> lock(m_mutex);
0396     Perf result;
0397     if (m_runstatus == RunStatus::Paused || m_runstatus == RunStatus::Failed || m_runstatus == RunStatus::Finished) {
0398         result.uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(m_time_at_finish - m_time_at_start).count();
0399     }
0400     else {
0401         result.uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(clock_t::now() - m_time_at_start).count();
0402     }
0403     for (auto& p : m_processed_event_counts) {
0404         auto level = p.first;
0405         auto event_count_at_start = p.second.first;
0406         auto event_count_at_finish = p.second.second;
0407         auto event_count_delta = event_count_at_finish - event_count_at_start;
0408         result.processed_event_counts[level] = event_count_delta;
0409         result.throughputs_hz[level] = (result.uptime_ms == 0) ? 0 : (event_count_delta * 1000.0 / result.uptime_ms);
0410     }
0411     result.runstatus = m_runstatus;
0412     result.thread_count = m_worker_states.size();
0413     result.event_level = m_ticker_level;
0414     result.event_count = result.processed_event_counts[result.event_level];
0415     result.throughput_hz = result.throughputs_hz[result.event_level];
0416     return result;
0417 }
0418 
0419 JExecutionEngine::Worker JExecutionEngine::RegisterWorker() {
0420     std::unique_lock<std::mutex> lock(m_mutex);
0421     auto mapping = m_topology->GetProcessorMapping();
0422     auto worker_id = m_worker_states.size();
0423     auto worker = std::make_unique<WorkerState>();
0424     worker->worker_id = worker_id;
0425     worker->is_stop_requested = false;
0426     worker->cpu_id = mapping.get_cpu_id(worker_id);
0427     worker->location_id = mapping.get_loc_id(worker_id);
0428     worker->thread = nullptr;
0429     m_worker_states.push_back(std::move(worker));
0430 
0431     bool pin_to_cpu = (mapping.get_affinity() != JProcessorMapping::AffinityStrategy::None);
0432     if (pin_to_cpu) {
0433         JCpuInfo::PinThreadToCpu(worker->thread, worker->cpu_id);
0434     }
0435     return {worker_id, &worker->backtrace};
0436 
0437 }
0438 
0439 
0440 void JExecutionEngine::RunWorker(Worker worker) {
0441 
0442     LOG_DEBUG(GetLogger()) << "Launched worker thread " << worker.worker_id << LOG_END;
0443     jana2_worker_id = worker.worker_id;
0444     jana2_worker_backtrace = worker.backtrace;
0445 #if JANA2_HAVE_PERFETTO
0446     JPerfettoService::RegisterCurrentThread(worker.worker_id);
0447 #endif
0448     try {
0449         Task task;
0450         while (true) {
0451             ExchangeTask(task, worker.worker_id);
0452             if (task.arrow == nullptr) break; // Exit as soon as ExchangeTask() stops blocking
0453             {
0454 #if JANA2_HAVE_PERFETTO
0455                 TRACE_EVENT("jana", perfetto::DynamicString{task.arrow->GetName()},
0456                     "worker_id", (uint64_t)worker.worker_id);
0457 #endif
0458                 task.arrow->Fire(task.input_event, task.outputs, task.output_count, task.status);
0459             }
0460         }
0461         LOG_DEBUG(GetLogger()) << "Stopped worker thread " << worker.worker_id << LOG_END;
0462     }
0463     catch(JException& ex) {
0464         LOG_ERROR(GetLogger()) << "Exception on worker thread " << worker.worker_id << ": " << ex.GetMessage();
0465         std::unique_lock<std::mutex> lock(m_mutex);
0466         m_runstatus = RunStatus::Failed;
0467         m_worker_states.at(worker.worker_id)->stored_exception = std::current_exception();
0468     }
0469     catch (...) {
0470         LOG_ERROR(GetLogger()) << "Exception on worker thread " << worker.worker_id << LOG_END;
0471         std::unique_lock<std::mutex> lock(m_mutex);
0472         m_runstatus = RunStatus::Failed;
0473         m_worker_states.at(worker.worker_id)->stored_exception = std::current_exception();
0474     }
0475 }
0476 
0477 
0478 void JExecutionEngine::ExchangeTask(Task& task, size_t worker_id, bool nonblocking) {
0479 
0480     auto checkin_time = std::chrono::steady_clock::now();
0481     // It's important to start measuring this _before_ acquiring the lock because acquiring the lock
0482     // may be a big part of the scheduler overhead
0483 
0484     std::unique_lock<std::mutex> lock(m_mutex);
0485     
0486     auto& worker = *m_worker_states.at(worker_id);
0487 
0488     if (task.arrow != nullptr) {
0489         CheckinCompletedTask_Unsafe(task, worker, checkin_time);
0490     }
0491 
0492     if (worker.is_stop_requested) {
0493         return;
0494     }
0495 
0496     FindNextReadyTask_Unsafe(task, worker);
0497 
0498     if (nonblocking) { return; }
0499     auto idle_time_start = clock_t::now();
0500     m_total_scheduler_duration += (idle_time_start - checkin_time);
0501 
0502     while (task.arrow == nullptr && !worker.is_stop_requested) {
0503         m_condvar.wait(lock);
0504         FindNextReadyTask_Unsafe(task, worker);
0505     }
0506     worker.last_checkout_time = clock_t::now();
0507 
0508     if (task.input_event != nullptr) {
0509         worker.last_event_nr = task.input_event->GetEventNumber();
0510     }
0511     else {
0512         worker.last_event_nr = 0;
0513     }
0514     m_total_idle_duration += (worker.last_checkout_time - idle_time_start);
0515 
0516     // Notify one worker, who will notify the next, etc, as long as FindNextReadyTaskUnsafe() succeeds.
0517     // After FindNextReadyTaskUnsafe fails, all threads block until the next returning worker reactivates the
0518     // notification chain.
0519     if (task.arrow != nullptr && task.arrow->IsParallel()) {
0520         m_condvar.notify_one();
0521     }
0522 }
0523 
0524 
0525 void JExecutionEngine::CheckinCompletedTask_Unsafe(Task& task, WorkerState& worker, clock_t::time_point checkin_time) {
0526 
0527     auto processing_duration = checkin_time - worker.last_checkout_time;
0528 
0529     ArrowState& arrow_state = m_arrow_states.at(worker.last_arrow_id);
0530 
0531     arrow_state.active_tasks -= 1;
0532     arrow_state.total_processing_duration += processing_duration;
0533 
0534     // Update event counts for arrow and topology (used for ticker and metrics)
0535     for (size_t output=0; output<task.output_count; ++output) {
0536         auto port_id = task.outputs[output].second;
0537         auto port = task.arrow->GetPort(port_id);
0538         auto level = task.outputs[output].first->GetLevel();
0539 
0540         if (port.GetContributesTopologyEventCounts()) {
0541             m_processed_event_counts[level].second++;
0542         }
0543         if (port.GetContributesArrowEventCounts()) {
0544             arrow_state.processed_event_counts[level]++;
0545         }
0546     }
0547 
0548     // Put each output in its correct queue or pool
0549     task.arrow->Push(task.outputs, task.output_count, worker.location_id);
0550 
0551     if (task.status == JArrow::FireResult::Finished) {
0552         // If this is an eventsource self-terminating (the only thing that returns Status::Finished right now) it will
0553         // have already called DoClose(). I'm tempted to always call DoClose() as part of JExecutionEngine::Finish() instead, however.
0554 
0555         // Mark arrow as finished
0556         arrow_state.status = ArrowState::Status::Finished;
0557 
0558         // Check if this switches the topology to Draining()
0559         if (m_runstatus == RunStatus::Running) {
0560             bool draining = true;
0561             for (auto& arrow: m_arrow_states) {
0562                 if (arrow.is_source && arrow.status == ArrowState::Status::Running) {
0563                     draining = false;
0564                 }
0565             }
0566             if (draining) {
0567                 m_runstatus = RunStatus::Draining;
0568             }
0569         }
0570     }
0571     worker.last_arrow_id = -1;
0572     worker.last_event_nr = 0;
0573 
0574     task.arrow = nullptr;
0575     task.input_event = nullptr;
0576     task.output_count = 0;
0577     task.status = JArrow::FireResult::NotRunYet;
0578 };
0579 
0580 
0581 void JExecutionEngine::FindNextReadyTask_Unsafe(Task& task, WorkerState& worker) {
0582 
0583     if (m_runstatus == RunStatus::Running || m_runstatus == RunStatus::Draining) {
0584         // We only pick up a new task if the topology is running or draining.
0585 
0586         // Each call to FindNextReadyTask_Unsafe() starts with a different m_next_arrow_id to ensure balanced arrow assignments
0587         size_t arrow_count = m_arrow_states.size();
0588         m_next_arrow_id += 1;
0589         m_next_arrow_id %= arrow_count;
0590 
0591         for (size_t i=m_next_arrow_id; i<(m_next_arrow_id+arrow_count); ++i) {
0592             size_t arrow_id = i % arrow_count;
0593 
0594             auto& state = m_arrow_states[arrow_id];
0595             if (!state.is_parallel && (state.active_tasks != 0)) {
0596                 // We've found a sequential arrow that is already active. Nothing we can do here.
0597                 LOG_TRACE(GetLogger()) << "Scheduler: Arrow with id " << arrow_id << " is unready: Sequential and already active." << LOG_END;
0598                 continue;
0599             }
0600 
0601             if (state.status != ArrowState::Status::Running) {
0602                 LOG_TRACE(GetLogger()) << "Scheduler: Arrow with id " << arrow_id << " is unready: Arrow is either paused or finished." << LOG_END;
0603                 continue;
0604             }
0605             // TODO: Support next_visit_time so that we don't hammer blocked event sources
0606 
0607             // See if we can obtain an input event (this is silly)
0608             JArrow* arrow = m_topology->GetArrows()[arrow_id];
0609             // TODO: consider setting state.next_input, retrieving via Fire()
0610             auto port = arrow->GetNextPortIndex();
0611             JEvent* event = (port == -1) ? nullptr : arrow->Pull(port, worker.location_id);
0612             if (event != nullptr || port == -1) {
0613                 LOG_TRACE(GetLogger()) << "Scheduler: Found next ready arrow with id " << arrow_id << LOG_END;
0614                 // We've found a task that is ready!
0615                 state.active_tasks += 1;
0616 
0617                 task.arrow = arrow;
0618                 task.input_port = port;
0619                 task.input_event = event;
0620                 task.output_count = 0;
0621                 task.status = JArrow::FireResult::NotRunYet;
0622 
0623                 worker.last_arrow_id = arrow_id;
0624                 if (event != nullptr) {
0625                     worker.is_event_warmed_up = event->IsWarmedUp();
0626                     worker.last_event_nr = event->GetEventNumber();
0627                 }
0628                 else {
0629                     worker.is_event_warmed_up = true; // Use shorter timeout
0630                     worker.last_event_nr = 0;
0631                 }
0632                 return;
0633             }
0634             else {
0635                 LOG_TRACE(GetLogger()) << "Scheduler: Arrow with id " << arrow_id << " is unready: Input event is needed but not on queue yet." << LOG_END;
0636             }
0637         }
0638     }
0639 
0640     // Because we reached this point, we know that there aren't any tasks ready,
0641     // so we check whether more are potentially coming. If not, we can pause the topology.
0642     // Note that our worker threads will still wait at ExchangeTask() until they get
0643     // shut down separately during Scale().
0644     
0645     if (m_runstatus == RunStatus::Pausing || m_runstatus == RunStatus::Draining) {
0646         // We want to avoid scenarios such as where the topology already Finished but then gets reset to Paused
0647         // This also leaves a cleaner narrative in the logs. 
0648 
0649         bool any_active_source_found = false;
0650         bool any_active_task_found = false;
0651         
0652         LOG_DEBUG(GetLogger()) << "Scheduler: No tasks ready" << LOG_END;
0653 
0654         for (size_t arrow_id = 0; arrow_id < m_arrow_states.size(); ++arrow_id) {
0655             auto& state = m_arrow_states[arrow_id];
0656             any_active_source_found |= (state.status == ArrowState::Status::Running && state.is_source);
0657             any_active_task_found |= (state.active_tasks != 0);
0658             // A source might have been deactivated by RequestPause, Ctrl-C, etc, and might be inactive even though it still has active tasks
0659         }
0660 
0661         if (!any_active_source_found && !any_active_task_found) {
0662             // Pause the topology
0663             m_time_at_finish = clock_t::now();
0664             m_runstatus = RunStatus::Paused;
0665             LOG_DEBUG(GetLogger()) << "Scheduler: Processing paused" << LOG_END;
0666             // I think this is the ONLY site where the topology gets paused. Verify this?
0667         }
0668     }
0669 
0670     worker.last_arrow_id = -1;
0671 
0672     task.arrow = nullptr;
0673     task.input_port = -1;
0674     task.input_event = nullptr;
0675     task.output_count = 0;
0676     task.status = JArrow::FireResult::NotRunYet;
0677 }
0678 
0679 
0680 void JExecutionEngine::PrintFinalReport() {
0681     // This is meant to handle exactly two scenarios:
0682     // 1. The user runs JANA by simply passing in a file and waiting for completion.
0683     //    In this case, PrintFinalReport() runs exactly once when the source finishes, and
0684     //    evt_count_at_start=0, and evt_count_delta = evt_count_at_finish. No confusion.
0685     //
0686     // 2. The user runs JANA interactively and/or intermittently, e.g. running scaling tests
0687     //    In this case, PrintFinalReport() runs every time the execution engine pauses,
0688     //    e.g. when the user presses Ctrl-C, or JBenchmarker calls Pause(). In this case, it shows
0689     //    how many events were processed since the last Run(), and with what throughput.
0690     //    Remember that throughput is always specific to the last Run/Pause interval.
0691 
0692     std::unique_lock<std::mutex> lock(m_mutex);
0693     auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(m_time_at_finish - m_time_at_start).count();
0694     auto thread_count = m_worker_states.size();
0695 
0696     std::ostringstream oss;
0697 
0698     oss << "\nOverall performance report:\n\n";
0699 
0700     size_t total_useful_ms = 0;
0701     for (auto& arrow_state : m_arrow_states) {
0702         auto useful_ms = std::chrono::duration_cast<std::chrono::milliseconds>(arrow_state.total_processing_duration).count();
0703         total_useful_ms += useful_ms;
0704     }
0705 
0706     for (auto& pair : m_processed_event_counts) {
0707         auto level = pair.first;
0708         auto evt_count_at_start = pair.second.first;
0709         auto evt_count_at_finish = pair.second.second;
0710         auto evt_count_delta = evt_count_at_finish - evt_count_at_start;
0711         auto throughput = evt_count_delta * 1000.0 / uptime_ms;
0712         oss << "  Completed " << evt_count_delta << " " << ToStringWithLowercasePlurals(level)
0713             << " at " << JTypeInfo::to_string_with_si_prefix(throughput) << "Hz avg\n";
0714     }
0715 
0716     auto total_scheduler_ms = std::chrono::duration_cast<std::chrono::milliseconds>(m_total_scheduler_duration).count();
0717     //auto total_idle_ms = std::chrono::duration_cast<std::chrono::milliseconds>(m_total_idle_duration).count();
0718 
0719     auto total_time_s = uptime_ms * thread_count / 1000.0;
0720     auto total_useful_time_s = total_useful_ms / 1000.0;
0721     auto total_scheduler_time_s = total_scheduler_ms / 1000.0;
0722     //auto total_idle_time_s = total_idle_ms / 1000.0;
0723     //auto total_lost_time_s = total_time_s - total_useful_time_s - total_scheduler_time_s - total_idle_time_s;
0724     oss << "\n";
0725     oss << "  Ran for " << std::setprecision(4) << uptime_ms/1000.0 << " seconds with " << thread_count << " worker threads\n";
0726     oss << "  Total useful time    [cpu-seconds]:  " << std::setprecision(6) << total_useful_time_s << " (" << std::setprecision(3) << total_useful_time_s/total_time_s*100 << " %)\n";
0727     oss << "  Total scheduler time [cpu-seconds]:  " << std::setprecision(6) << total_scheduler_time_s << " (" << std::setprecision(3) << total_scheduler_time_s/total_time_s*100 << " %)\n";
0728     oss << "\nArrow performance report:\n\n";
0729 
0730     for (size_t arrow_id=0; arrow_id < m_arrow_states.size(); ++arrow_id) {
0731         auto* arrow = m_topology->GetArrows()[arrow_id];
0732         auto& arrow_state = m_arrow_states[arrow_id];
0733         auto useful_ms = std::chrono::duration_cast<std::chrono::milliseconds>(arrow_state.total_processing_duration).count();
0734         total_useful_ms += useful_ms;
0735 
0736         oss << "  - " << arrow->GetName() << " (" << (arrow->IsParallel() ? "parallel" : "sequential") << ")\n";
0737 
0738         for (auto& pair : arrow_state.processed_event_counts) {
0739             auto level = pair.first;
0740             auto events_processed = pair.second;  // We don't need 
0741             auto throughput_per_worker = events_processed * 1000.0 / useful_ms;
0742             auto throughput_bottleneck = arrow->IsParallel() ? throughput_per_worker * thread_count : throughput_per_worker;
0743             if (arrow->IsParallel()) {
0744                 oss << "    Processed " << events_processed << " " << ToStringWithLowercasePlurals(level)
0745                     << " at " << JTypeInfo::to_string_with_si_prefix(throughput_per_worker) << "Hz effective per worker ("
0746                     << JTypeInfo::to_string_with_si_prefix(throughput_bottleneck) << "Hz max)\n";
0747             }
0748             else {
0749                 oss << "    Processed " << events_processed << " " << ToStringWithLowercasePlurals(level)
0750                     << " at " << JTypeInfo::to_string_with_si_prefix(throughput_per_worker) << "Hz effective\n";
0751             }
0752         }
0753         oss << "\n";
0754     }
0755 
0756 
0757     LOG_INFO(GetLogger()) << oss.str();
0758 }
0759 
0760 void JExecutionEngine::SetTickerEnabled(bool show_ticker) {
0761     m_show_ticker = show_ticker;
0762 }
0763 
0764 bool JExecutionEngine::IsTickerEnabled() const {
0765     return m_show_ticker;
0766 }
0767 
0768 void JExecutionEngine::SetTimeoutEnabled(bool timeout_enabled) {
0769     m_enable_timeout = timeout_enabled;
0770 }
0771 
0772 bool JExecutionEngine::IsTimeoutEnabled() const {
0773     return m_enable_timeout;
0774 }
0775 
0776 JArrow::FireResult JExecutionEngine::Fire(size_t arrow_id, size_t location_id) {
0777 
0778     std::unique_lock<std::mutex> lock(m_mutex);
0779     if (arrow_id >= m_topology->GetArrows().size()) {
0780         LOG_WARN(GetLogger()) << "Firing unsuccessful: No arrow exists with id=" << arrow_id << LOG_END;
0781         return JArrow::FireResult::NotRunYet;
0782     }
0783     JArrow* arrow = m_topology->GetArrows()[arrow_id];
0784     LOG_WARN(GetLogger()) << "Attempting to fire arrow with name=" << arrow->GetName() 
0785                           << ", index=" << arrow_id << ", location=" << location_id << LOG_END;
0786 
0787     ArrowState& arrow_state = m_arrow_states[arrow_id];
0788     if (arrow_state.status == ArrowState::Status::Finished) {
0789         LOG_WARN(GetLogger()) << "Firing unsuccessful: Arrow status is Finished." << arrow_id << LOG_END;
0790         return JArrow::FireResult::Finished;
0791     }
0792     if (!arrow_state.is_parallel && arrow_state.active_tasks != 0) {
0793         LOG_WARN(GetLogger()) << "Firing unsuccessful: Arrow is sequential and already has an active task." << arrow_id << LOG_END;
0794         return JArrow::FireResult::NotRunYet;
0795     }
0796     arrow_state.active_tasks += 1;
0797 
0798     auto port = arrow->GetNextPortIndex();
0799     JEvent* event = nullptr;
0800     if (port != -1) {
0801         event = arrow->Pull(port, location_id);
0802         if (event == nullptr) {
0803             LOG_WARN(GetLogger()) << "Firing unsuccessful: Arrow needs an input event from port " << port << ", but the queue or pool is empty." << LOG_END;
0804             arrow_state.active_tasks -= 1;
0805             return JArrow::FireResult::NotRunYet;
0806         }
0807         else {
0808             LOG_WARN(GetLogger()) << "Input event #" << event->GetEventNumber() << " from port " << port << LOG_END;
0809         }
0810     }
0811     else {
0812         LOG_WARN(GetLogger()) << "No input events" << LOG_END;
0813     }
0814     lock.unlock();
0815 
0816     size_t output_count;
0817     JArrow::OutputData outputs;
0818     JArrow::FireResult result = JArrow::FireResult::NotRunYet;
0819 
0820     LOG_WARN(GetLogger()) << "Firing arrow" << LOG_END;
0821     arrow->Fire(event, outputs, output_count, result);
0822     LOG_WARN(GetLogger()) << "Fired arrow with result " << ToString(result) << LOG_END;
0823     if (output_count == 0) {
0824         LOG_WARN(GetLogger()) << "No output events" << LOG_END;
0825     }
0826     else {
0827         for (size_t i=0; i<output_count; ++i) {
0828             LOG_WARN(GetLogger()) << "Output event #" << outputs.at(i).first->GetEventNumber() << " on port " << outputs.at(i).second << LOG_END;
0829         }
0830     }
0831 
0832     lock.lock();
0833     arrow->Push(outputs, output_count, location_id);
0834     arrow_state.active_tasks -= 1;
0835     lock.unlock();
0836     return result;
0837 }
0838 
0839 
0840 void JExecutionEngine::HandleSIGINT() {
0841     InterruptStatus status = m_interrupt_status;
0842     std::cout << std::endl;
0843     switch (status) {
0844         case InterruptStatus::NoInterruptsSupervised: m_interrupt_status = InterruptStatus::InspectRequested; break;
0845         case InterruptStatus::InspectRequested: m_interrupt_status = InterruptStatus::PauseAndQuit; break;
0846         case InterruptStatus::NoInterruptsUnsupervised:
0847         case InterruptStatus::PauseAndQuit:
0848         case InterruptStatus::InspectInProgress: 
0849             _exit(-2);
0850     }
0851 }
0852 
0853 void JExecutionEngine::HandleSIGUSR1() {
0854     m_send_worker_report_requested = true;
0855 }
0856 
0857 void JExecutionEngine::HandleSIGUSR2() {
0858     if (jana2_worker_backtrace != nullptr) {
0859         jana2_worker_backtrace->Capture(3);
0860     }
0861 }
0862 
0863 void JExecutionEngine::HandleSIGTSTP() {
0864     std::cout << std::endl;
0865     m_print_worker_report_requested = true;
0866 }
0867 
0868 void JExecutionEngine::PrintWorkerReport(bool send_to_pipe) {
0869 
0870     std::unique_lock<std::mutex> lock(m_mutex);
0871     LOG_INFO(GetLogger()) << "Generating worker report. It may take some time to retrieve each symbol's debug information." << LOG_END;
0872     for (auto& worker: m_worker_states) {
0873         worker->backtrace.Reset();
0874         pthread_kill(worker->thread->native_handle(), SIGUSR2);
0875     }
0876     for (auto& worker: m_worker_states) {
0877         worker->backtrace.WaitForCapture();
0878     }
0879     std::ostringstream oss;
0880     oss << "Worker report" << std::endl;
0881     for (auto& worker: m_worker_states) {
0882         oss << "------------------------------" << std::endl 
0883             << "  Worker:        " << worker->worker_id << std::endl
0884             << "  Current arrow: " << worker->last_arrow_id << std::endl
0885             << "  Current event: " << worker->last_event_nr << std::endl
0886             << "  Backtrace:" << std::endl << std::endl
0887             << worker->backtrace.ToString();
0888     }
0889     auto s = oss.str();
0890     LOG_WARN(GetLogger()) << s << LOG_END;
0891 
0892     if (send_to_pipe) {
0893 
0894         int fd = open(m_path_to_named_pipe.c_str(), O_WRONLY);
0895         if (fd >= 0) {
0896             write(fd, s.c_str(), s.length()+1);
0897             close(fd);
0898         }
0899         else {
0900             LOG_ERROR(GetLogger()) << "Unable to open named pipe '" << m_path_to_named_pipe << "' for writing. \n"
0901             << "  You can use a different named pipe for status info by setting the parameter `jana:status_fname`.\n"
0902             << "  The status report will still show up in the log." << LOG_END;
0903         }
0904     }
0905 }
0906 
0907 
0908 std::string ToString(JExecutionEngine::RunStatus runstatus) {
0909     switch(runstatus) {
0910         case JExecutionEngine::RunStatus::Running: return "Running";
0911         case JExecutionEngine::RunStatus::Paused: return "Paused";
0912         case JExecutionEngine::RunStatus::Failed: return "Failed";
0913         case JExecutionEngine::RunStatus::Pausing: return "Pausing";
0914         case JExecutionEngine::RunStatus::Draining: return "Draining";
0915         case JExecutionEngine::RunStatus::Finished: return "Finished";
0916         default: return "CorruptedRunStatus";
0917     }
0918 }
0919