Database-based thread stack information acquisition method, apparatus, equipment, and medium
By creating a log file under the protection of a mutex lock and traversing the thread manager, the target thread is interrupted to obtain thread stack information. This solves the difficulty of thread stack acquisition in the prior art, realizes safe and standard thread stack information acquisition, and improves fault diagnosis efficiency.
Patent Information
- Application Number
- CN202611322381.4
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-28
- Publication Date
- 2026-11-17
AI Technical Summary
Existing technologies face difficulties in collecting thread stack information in container environments, minimal systems, or production hardened environments. They lack a unified triggering mechanism and standardized output, and signal handling functions are prone to causing process crashes or deadlocks, failing to meet the needs for rapid response and automated diagnosis.
The system receives trigger signals through a dedicated signal processing thread, creates a log file under the protection of a mutex lock, traverses the global thread manager, delivers acquisition signals, interrupts the target thread, saves the register context, switches to user mode to execute the interrupt service function, obtains and writes the thread stack information, and restores the thread state.
It enables safe, standardized, and controllable thread stack acquisition in production environments, improving the efficiency of system fault diagnosis and maintenance recovery, reducing the impact on threads, and meeting the stringent requirements of modern production environments.
Smart Images

Figure CN123114783A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of data processing technology, and in particular to a method, apparatus, device, and medium for acquiring thread stack information based on a database. Background Technology
[0002] During process execution, issues such as freezing, deadlocks, prolonged unresponsiveness, or abnormal time consumption frequently occur. The key to locating these faults lies in obtaining the thread-level runtime environment, especially the thread stack information of each thread, to accurately analyze blocking points, lock contention, wait queues, and hot functions. In practice, one common technique for obtaining thread stacks is to use debuggers or diagnostic tools to attach online. While this method typically yields relatively complete runtime data, its drawbacks are also significant. The tools themselves require additional installation and maintenance support, and may not be deployable in container environments, minimal systems, or hardened production environments. The attach action may cause process pauses, performance fluctuations, and even security audit risks. This method often relies on manual remote login and operation, resulting in low automation levels and difficulty in meeting the needs for rapid response to sudden faults. In scenarios with restricted permissions or strict security policies, such tools may even be directly prohibited.
[0003] Another common approach is to use operating system signals to trigger diagnostic actions, that is, to use specific signals (such as the kill command) to prompt processes to actively print status information. This method requires no additional ports or tool dependencies, is easy to operate, and is suitable for quickly locating problems in production environments. However, existing signal-triggered implementations have many drawbacks: the lack of a unified triggering mechanism and standardized output format for "thread stacks" leads to insufficient information availability; if complex operations are directly executed in the signal handling function, it is easy to touch the unsafe boundaries of asynchronous signals, which may cause process crashes or secondary deadlocks; support for multi-threaded scenarios is imperfect, making it difficult to guarantee the collection of stack snapshots of all threads; and it is impossible to effectively control key aspects such as log writing to disk, output frequency, storage path, and information integrity, limiting its practical value in automated operation and maintenance and refined diagnosis. In summary, existing technologies each have their limitations, and there is an urgent need for a safer, more standardized, and controllable thread stack acquisition solution to meet the stringent requirements of modern production environments. Summary of the Invention
[0004] The main objective of this invention is to provide a database-based method, apparatus, device, and storage medium for collecting thread stack information, aiming to solve the technical problem that the existing technology lacks the ability to centrally and sort the display of the volume information of all files in a project, which makes it impossible for developers to quickly understand the distribution of file volumes in the project.
[0005] To achieve the above objectives, the present invention provides a database-based method for collecting thread stack information, comprising: The first trigger signal is received by a dedicated signal processing thread; In response to the first trigger signal, the dedicated signal processing thread creates a unified log file based on the current timestamp and writes a metadata header into the unified log file under the protection of a mutex lock. After completing the writing operation, the unified log file is closed and the mutex lock is released. After releasing the mutex lock, the dedicated signal processing thread traverses each thread in the global thread manager to obtain the lightweight process ID of each thread, and sends the second acquisition signal to the target thread using the lightweight process ID as the addressing parameter. When the target thread receives the second acquisition signal, it interrupts the current execution flow of the target thread at the instruction boundary, saves the register context on the user-mode stack of the target thread and sets the instruction pointer to the entry address of the interrupt service function, and switches the target thread from kernel mode to user mode; In the user mode, the central processing unit executes the interrupt service function according to the entry address; The interrupt service function performs a stack backtracking operation to obtain thread stack information, and under the protection of a mutex lock, writes the thread stack information into the unified log file. After the interrupt service function is completed, the execution state of the target thread before the interrupt is restored based on the register context.
[0006] Furthermore, to achieve the above objectives, the present invention provides a database-based thread stack information acquisition device, comprising: An external trigger module is used to receive the first trigger signal by a dedicated signal processing thread; The centralized preparation module is used to respond to the first trigger signal, and the dedicated signal processing thread creates a unified log file based on the current timestamp and writes the metadata header into the unified log file under the protection of a mutex lock. After completing the writing operation, the unified log file is closed and the mutex lock is released. The traversal broadcast module is used to traverse each thread in the global thread manager through the dedicated signal processing thread after the mutex is released, obtain the lightweight process ID of each thread, and send the second acquisition signal to the target thread with the lightweight process ID as the addressing parameter. The process interruption module is used to interrupt the current execution flow of the target thread at the instruction boundary when the target thread receives the second acquisition signal, save the register context on the user-mode stack of the target thread and set the instruction pointer to the entry address of the interrupt service function, and switch the target thread from kernel mode to user mode. The function execution module is used in the user mode for the central processing unit to execute the interrupt service function according to the entry address; The stack backtracking module is used to perform stack backtracking operations through the interrupt service function, obtain thread stack information, and write the thread stack information into the unified log file under the protection of a mutex lock. The process recovery module is used to restore the execution state of the target thread before the interruption based on the register context after the interrupt service function has been executed.
[0007] Furthermore, to achieve the above objectives, the present invention also provides a computer device, the computer device including a memory, a processor, and a database-based thread stack information acquisition program stored in the memory and executable on the processor, wherein when the database-based thread stack information acquisition program is executed by the processor, it implements the steps of the database-based thread stack information acquisition method described above.
[0008] Furthermore, to achieve the above objectives, the present invention also provides a computer-readable storage medium storing a database-based thread stack information acquisition program, wherein when the database-based thread stack information acquisition program is executed by a processor, it implements the steps of the database-based thread stack information acquisition method described above.
[0009] Beneficial Effects: This invention relates to the field of data processing technology and discloses a database-based method, apparatus, device, and medium for collecting thread stack information. The method includes: a dedicated signal processing thread receiving a first trigger signal, creating a timestamped log file and writing header information under mutex lock protection, and then releasing the lock; traversing the global thread manager and sending a second collection signal to each target thread; the target thread interrupting its current execution at the instruction boundary, saving the register context, pointing the instruction pointer to the interrupt service function entry point, and switching to user mode to execute the function; after stack backtracking is completed within the function, the thread stack information is written to the same log file; when the function returns, the register context is restored, the thread continues execution from the interrupt point, and the interrupted system call is retried according to the automatic restart flag. This invention automatically generates a unified stack log with timestamped identifiers through centralized processing of trigger signals and a thread self-collection mechanism, and summarizes the entire thread's execution state and register context, helping maintenance personnel to intuitively locate the root cause of blocking and deadlock, thus improving the efficiency of system fault diagnosis and maintenance recovery. Attached Figure Description
[0010] The present invention will be further described below with reference to the accompanying drawings and embodiments. In the accompanying drawings: Figure 1 This is a schematic diagram of an application environment for a database-based thread stack information acquisition method according to an embodiment of the present invention; Figure 2 This is a flowchart illustrating an embodiment of the database-based thread stack information acquisition method of the present invention; Figure 3 This is a schematic diagram of the functional modules of a preferred embodiment of the database-based thread stack information acquisition device of the present invention; Figure 4 This is a schematic diagram of the structure of a computer device according to an embodiment of the present invention; Figure 5 This is another structural schematic diagram of a computer device according to one embodiment of the present invention. Detailed Implementation
[0011] It should be understood that the specific embodiments described herein are for illustrative purposes only and are not intended to limit the scope of the invention.
[0012] The database-based thread stack information acquisition method provided in this invention can be applied to applications such as... Figure 1 In this application environment, the client communicates with the server via a network. The server, through a dedicated signal processing thread, receives the first trigger signal, creates a timestamped log file under mutex protection, writes header information, and then releases the lock. It then traverses the global thread manager, sending a second acquisition signal to each target thread. The target thread interrupts its current execution at the instruction boundary, saves its register context, points the instruction pointer to the interrupt service function entry point, and switches to user mode to execute the function. After stack backtracking within the function, the thread stack information is written to the same log file. When the function returns, the register context is restored, the thread continues execution from the interrupt point, and the interrupted system call is retried with an automatic restart flag. This invention, through centralized trigger signal processing and thread self-acquisition mechanism, automatically generates a unified stack log with timestamped identifiers and summarizes the entire thread's runtime environment and register context, helping maintenance personnel intuitively locate the root causes of blocking and deadlocks, improving system fault diagnosis and maintenance recovery efficiency. The client can be, but is not limited to, various personal computers, laptops, smartphones, tablets, and portable wearable devices. The server can be implemented using a standalone server or a server cluster consisting of multiple servers. The following detailed description of specific embodiments further illustrates this invention.
[0013] Please see Figure 2 , Figure 2 This is a flowchart illustrating an embodiment of the database-based thread stack information acquisition method provided by the present invention. It should be noted that although the logical order is shown in the flowchart, in some cases, the steps shown or described may be performed in a different order than that shown here.
[0014] like Figure 2 As shown, the database-based thread stack information acquisition method proposed in this invention includes the following steps: S100, The first trigger signal is received by a dedicated signal processing thread; S200. In response to the first trigger signal, the dedicated signal processing thread creates a unified log file based on the current timestamp and writes a metadata header into the unified log file under the protection of the mutex lock. After completing the writing operation, the unified log file is closed and the mutex lock is released. S300. After releasing the mutex lock, the dedicated signal processing thread traverses each thread in the global thread manager to obtain the lightweight process ID of each thread, and sends the second acquisition signal to the target thread using the lightweight process ID as the addressing parameter. S400. When the target thread receives the second acquisition signal, the current execution flow of the target thread is interrupted at the instruction boundary, the register context is saved on the user-mode stack of the target thread and the instruction pointer is set to the entry address of the interrupt service function, and the target thread is switched from kernel mode to user mode. S500. In the user mode, the central processing unit executes the interrupt service function according to the entry address; S600. Perform a stack backtracking operation through the interrupt service function to obtain thread stack information, and write the thread stack information into the unified log file under the protection of a mutex lock. S700. After the interrupt service function is completed, the execution state of the target thread before the interrupt is restored based on the register context.
[0015] In this embodiment, the process begins with an external trigger. The operations and maintenance personnel send a first trigger signal to the target database process using the kill command (signal sending command) provided by the operating system. This signal is designed to be blocked in the signal mask of all ordinary worker threads, thus not interfering with their normal execution. Only a pre-created dedicated signal handling thread receives this signal through a synchronous waiting mechanism (such as sigwait), ensuring centralized control over the triggering action.
[0016] Upon receiving the first trigger signal, the dedicated signal handling thread immediately enters the centralized preparation phase. This phase is strictly protected by a mutex to avoid resource contention with subsequent multi-threaded writes. Specific operations include: extracting the storage path from the database's error log directory configuration, generating a unique output filename based on the current system timestamp, and opening the file in write-only, create-and-truncate (O_WRONLY|O_CREAT|O_TRUNC) mode as the unified log file for this stack trace. Subsequently, a metadata header is written to this file, containing global diagnostic context such as the timestamp, database version number, and build information. Immediately after writing the header, the file handle is closed and the mutex is released. This phase is extremely short, and the lock's holding scope is strictly controlled, ensuring no impact on subsequent broadcast operations.
[0017] After releasing the mutex, the dedicated signal handling thread enters the external broadcast phase. It iterates through all thread metadata objects registered in the Global Thread Manager, performing multi-level filtering on each thread: skipping system auxiliary threads, skipping the signal handling thread itself, skipping idle or soon-to-be-closed connection threads, and skipping threads that cannot obtain the operating system kernel's Lightweight Process ID (LWP ID). For target threads that pass the filtering, it calls the extended thread information query interface to retrieve their kernel-level thread identifier (LWP ID) from the pre-stored fields of the thread metadata structure. If this identifier is valid (greater than zero), it uses a kernel-level thread signal delivery system call (such as tgkill) to precisely locate the target thread using both the process ID (PID) and the target thread identifier (TID), and sends a second acquisition signal to that thread. The broadcaster returns immediately after sending the signal, without waiting for any target thread to complete stack sampling, thus avoiding prolonged blocking of the broadcast thread.
[0018] Upon receiving the second acquisition signal, the target thread's current execution flow is interrupted by the operating system kernel. Specifically, the kernel responds to the signal at the target thread's current instruction boundary (i.e., the checkpoint after each machine instruction has been executed), rather than interrupting at an arbitrary location. At this time, the kernel automatically allocates and fills a stack frame structure on the target thread's user-space stack. This structure fully stores the CPU register context at the moment of interruption, including the instruction pointer (IP), stack pointer (SP), frame pointer (FP), and the values of all general-purpose registers. Simultaneously, the kernel modifies the target thread's instruction pointer to the entry address of the pre-registered acquisition signal interrupt service function and adjusts the stack pointer to the space reserved above the stack frame for the service function. Subsequently, the target thread returns from kernel mode to user mode and begins executing the interrupt service function.
[0019] During the execution of the interrupt service routine in user mode, the CPU executes the specific stack backtracking and information acquisition logic according to the entry address. This function first opens the unified log file created in the first phase in append mode (O_APPEND) under mutex protection, ensuring that concurrent writing by multiple threads does not overwrite each other's contents. Next, it calls the asynchronous signal-safe formatted output module, which allocates a buffer entirely on the stack and implements its own integer-to-string conversion algorithm, without relying on any heap memory allocation, standard library functions, or global state, thus avoiding the unsafety issues of asynchronous signals in the signal handling context. When collecting thread diagnostic information, it outputs the thread's user-mode identifier (such as the thread name or number within the database), kernel lightweight process ID (LWP ID), current stack bottom pointer address, stack size, and the currently executing database Structured Query Language (SQL) statement (truncated to 1 megabyte to control output size), as well as business semantic information such as the database connection identifier and the thread's killed status.
[0020] Stack backtracking is performed using the Stack Backtracking Safe Call Module, whose algorithm is based on the linked list call chain maintained by the CPU frame pointer register. Starting from the current frame pointer, it sequentially reads the return address (e.g., 8 bytes off the frame pointer in a 64-bit system) and the previous frame pointer (located at the position pointed to by the frame pointer) stored in each stack frame, looping until the frame pointer is null or the preset frame limit is reached. In signal interruption scenarios, the call stack from top to bottom includes the interrupt handler's own stack frame, the signal trampoline, the kernel-saved context (where the frame pointer is frozen to the value at the time of the interruption), and the interrupted business code call chain. The symbolization process directly uses a version that supports file descriptor writing, without delayed resolution or dynamic memory operations, ensuring reliable operation even in constrained environments. All collected stack frame addresses and symbol information, along with the aforementioned diagnostic fields, are formatted and written to a unified log file, and finally the file is closed and the mutex is released.
[0021] After the interrupt service routine completes, it triggers the operating system's signal recovery system call (such as sigreturn in Linux). The kernel restores all registers to their original values from the previously saved stack frame structure, especially resetting the instruction pointer to the address of the next instruction after the interruption. The stack pointer and frame pointer are also restored to their pre-interrupt states. At this point, the target thread seamlessly resumes execution from the breakpoint, as if no interruption had occurred. Because the slow system call auto-restart flag (SA_RESTART) is set when registering the signal handling function, if the thread was previously executing slow system calls such as reading / writing files or waiting for network I / O, the system call will automatically retry without returning an error code due to signal interruption, thus ensuring the transparency of business operations.
[0022] Finally, after all worker threads that received the acquisition signal completed the above self-acquisition process in sequence, a unified log file compiled stack snapshots of all threads. Because each thread writes serially via a mutex lock, the stack blocks of each thread in the file are arranged in the order they acquired the lock, and each block contains complete thread identifiers, register contexts, call stacks, and business state information. Operations personnel can directly read this file to quickly locate deadlocks, blocking points, or hot functions. The entire process's impact on the target process is equivalent to executing only a few additional lightweight function calls—a single acquisition takes between tens of microseconds and milliseconds. Even if hundreds of threads concurrently enter the interrupt, due to the serialized file writing, the waiting time for the last thread is only about a few milliseconds, barely interfering with normal business processing. The entire method does not rely on an external debugger, requires no process attachment or thread pausing, and is entirely based on standard operating system signal mechanisms and self-implemented asynchronous safety components, achieving low-intrusion, highly reliable, and rapid thread stack diagnosis in production environments.
[0023] In one embodiment, prior to S100, the following steps are specifically included: During the database process startup phase, the first trigger signal is added to the signal mask of each thread to block the delivery of the first trigger signal to each thread; The dedicated signal processing thread receives the first trigger signal through a synchronous waiting method, and triggers the full stack acquisition process after receiving the first trigger signal. Set the second acquisition signal to a signal mask that does not enter each thread, and register the interrupt service function corresponding to the second acquisition signal for each thread; When registering the interrupt service function, set the extended signal information flag and the slow system call auto-restart flag for the interrupt service function.
[0024] In this embodiment, during the initialization and startup phase of the database process, two real-time signals need to be deployed and registered differently. This is a prerequisite for the safe operation of the entire stack acquisition scheme. First, for the first trigger signal, the system calls the thread signal mask setting interface (such as pthread_sigmask) to add the signal to the signal mask of all ordinary worker threads, thereby blocking its delivery to these threads. This means that when this signal is sent externally via the kill command, ordinary worker threads will not be aware of or respond to it; only the pre-designated dedicated signal handling thread is not subject to this blocking rule. This dedicated thread removes the signal from its own signal mask upon startup and enters an infinite loop, blockingly waiting for the signal to arrive through a synchronous wait interface (such as sigwaitinfo or sigtimedwait). This synchronous wait mechanism is the "master switch" of the signal-driven acquisition process—once the dedicated thread receives the first trigger signal, it immediately triggers the subsequent full stack acquisition process without being subject to strict context constraints like asynchronous signal processing.
[0025] In stark contrast to the first trigger signal, the second acquisition signal is designed as a signal mask that does not enter any thread, ensuring that it can interrupt the execution of all worker threads. To achieve this, the system registers an interrupt service function corresponding to the second acquisition signal for each worker thread during startup. The registration process is completed through the signal installation interface provided by the operating system (such as the sigaction structure). During registration, two crucial flags must be configured for the interrupt service function to ensure its reliability and business transparency in the production environment.
[0026] The first flag is the extended signal information flag (SA_SIGINFO). When this flag is enabled, the operating system will additionally pass a signal information structure containing the sender's process ID when the interrupt service routine is called. This design allows threads to accurately determine the source of signals during stack trace acquisition: if the signal originates from within the same process (broadcast by a dedicated signal handling thread), the stack information is uniformly written to a pre-created global log file; if the signal originates from an external process (e.g., due to operator error or a separate message from a debugging tool), it falls back to standard error output (stderr). This sender-based output routing mechanism ensures both the cleanliness of internal automated data collection and the flexibility of external ad-hoc diagnostics, avoiding log pollution or permission conflicts.
[0027] The second flag is the slow system call automatic restart flag (SA_RESTART). When the target thread receives a second signal while executing some potentially blocking slow system calls (such as read, write, accept, or futex system calls waiting for a lock), the kernel will interrupt the current call to execute the signal handler. If this flag is not set, these system calls will typically return -1 with the error code EINTR (indicating interruption by a signal), requiring explicit handling of retries in the business logic, increasing code complexity and the potential risk of data loss. With the SA_RESTART flag enabled, the kernel will automatically restart the interrupted system call when the interrupt service function returns, allowing it to continue execution from the breakpoint as if no interruption had occurred. This mechanism ensures the transparency and seamlessness of core database I / O operations and network communication, greatly reducing disruption to online services.
[0028] Furthermore, special attention must be paid to reentrancy protection configuration when registering interrupt service functions. The system does not set a flag allowing nested signals (i.e., SA_NODEFER remains off by default). This means that when a thread is executing an interrupt service function for a second acquired signal, the kernel automatically adds the signal to the thread's signal mask to block it. If the signal arrives again during processing, the kernel will not immediately interrupt the current processing flow, but will place it in a processing queue; after the current interrupt service function returns and the kernel restores the thread's original signal mask, it will check the queue and deliver the second signal. This default behavior, combined with the single mutex principle designed in the system, fundamentally eliminates the risk of self-deadlock caused by signal handler reentrancy—because the mutex is released when the first handler function returns, and the lock is available when it enters again, thus ensuring the safety and stability of the multi-threaded concurrent acquisition process. At this point, the registration of dual signals, mask isolation, and flag configuration are all complete, laying a solid runtime foundation for subsequent triggering, broadcasting, and self-acquisition.
[0029] In one embodiment, S200 includes: The dedicated signal processing thread extracts the directory path from the database's error log directory; A unique filename is generated based on the directory path and the current system timestamp, and a unified log file is created using the unique filename. The dedicated signal processing thread opens the unified log file in a preset write mode and writes the timestamp of the trigger time and the database version number as the metadata header into the unified log file. After completing the writing operation of the metadata header, close the unified log file and release the mutex lock.
[0030] In this embodiment, after receiving the first trigger signal and successfully acquiring the mutex, the dedicated signal processing thread immediately enters the creation and initialization phase of the unified log file. The primary operation in this phase is to extract the path string of the error log directory from the database's global configuration structure. This directory is usually determined by configuration files or command-line parameters when the database process starts and serves as the unified root path for all diagnostic logs (including error logs, alarm logs, and the current stack snapshot). After extracting the directory path, the thread calls the system time acquisition interface provided by the operating system (such as gettimeofday or clock_gettime) to obtain the current calendar time and formats it into a high-precision timestamp string (accurate to microseconds or even nanoseconds, typically using a fixed-width format of YYYYMMDD-HHMMSS-uuuuuu). Then, the timestamp is concatenated with a preset filename prefix (such as stack_trace) and suffix (such as .log) to generate a globally unique output filename. Because the timestamp has strict increment and uniqueness, even if it is triggered multiple times within the same microsecond, different processes or different numbers of triggers will not cause filename conflicts. It also facilitates subsequent retrieval and archiving in chronological order.
[0031] After generating a unique filename, a dedicated signal processing thread opens the unified log file in a preset write mode. The "preset write mode" here specifically refers to the combination of write-only, create-and-truncate (O_WRONLY | O_CREAT | O_TRUNC) in the operating system's file open flags: O_WRONLY indicates that only write operations are allowed; O_CREAT ensures that the file is automatically created if it does not exist; O_TRUNC guarantees that if a file with the same name already exists (due to a very low probability timestamp conflict or manual pre-creation), its original content will be completely cleared, thus ensuring that the stack information collected this time is written from an empty file, avoiding interference from historical residual data. Upon successful opening, the thread immediately writes the metadata header to the file. The metadata header contains at least two core diagnostic contexts: a timestamp of the trigger time (accurate to microseconds, used to correlate the time of the fault occurrence) and a database version number (including the major version, minor version, and build number, used to trace differences in function symbols and code path changes between different versions). In addition, depending on the specific implementation plan, additional build information (such as compilation date, compiler version, optimization level, etc.) may be written, which has important auxiliary value for subsequent symbolic resolution and problem reproduction.
[0032] Once all bytes of the metadata header have been successfully written to disk, a dedicated signal handling thread actively invokes a file close system call (such as `close`) to close the file descriptor of the unified log file. The close operation forces the header data in the operating system's page cache to be flushed to the storage device, preventing header loss due to subsequent process crashes; it also releases the file descriptor resource, preventing resource leaks. After closing, the thread immediately releases the previously held mutex lock. It is important to emphasize that the entire file creation, header writing, and closing process is performed within the protection of the mutex lock, but because the operation only involves a fixed-length header (typically only a few hundred bytes) and does not involve any complex string formatting or dynamic memory allocation, the lock holding time is strictly controlled at the microsecond level. Releasing the mutex is a key turning point connecting the "centralized preparation" and "external broadcast" phases. From this point onward, the signal processing thread no longer holds any locks while iterating through all worker threads and sending the second acquisition signal. This ensures that each subsequent target thread can immediately compete to acquire the mutex and append its stack information when entering the interrupt service function, without unnecessary blocking due to waiting for the signal processing thread to release the lock. This fully implements the core concurrency design principle of "short holding and external broadcast" in the system.
[0033] In one embodiment, S300 includes: When iterating through the threads in the global thread manager, the dedicated signal processing thread performs a filtering operation on each thread in turn. Skip system auxiliary threads, dedicated signal handling threads, connection threads that are idle or about to be closed, and threads whose valid lightweight process IDs cannot be obtained from the thread metadata structure to obtain the target thread; The target thread is analyzed, and a lightweight process ID is obtained from the target thread's metadata structure. The second acquisition signal is sent to the target thread using the process identifier of the current database process and the lightweight process number as two parameters.
[0034] In this embodiment, after the creation of the unified log file and the release of the mutex lock are completed, the dedicated signal processing thread enters the external broadcast phase. Its core task is to traverse all thread metadata objects registered in the Global Thread Manager. The Global Thread Manager is a centralized registry maintained internally by the database process, recording the context information of all business threads in the process, including the thread's user-mode identifier, kernel lightweight process ID (LWP ID), current state (running, idle, shutting down), and type label (system auxiliary or business processing). The traversal process does not indiscriminately send collection signals to every thread, but rather performs a rigorous four-layer filtering operation for each thread to ensure the accuracy and security of the broadcast.
[0035] The first layer of filtering skips system auxiliary threads. These threads typically handle background maintenance tasks such as log flushing, statistics collection, and memory page cleanup. Their call stacks usually lack direct diagnostic value for locating deadlocks or blocking issues at the business level, and forced interruption may affect the internal stability of the system. The second layer of filtering skips dedicated signal handling threads themselves, as these threads have already completed trigger processing and broadcasting, and their stack states are irrelevant to the current fault situation. More importantly, it avoids sending signals to themselves, which could lead to unnecessary recursion or logical confusion. The third layer of filtering skips idle threads (i.e., sleeping and waiting for new tasks) or connection threads that are about to close. These threads neither hold business locks nor execute any valid SQL operations; collecting their stacks would only increase the output file size without providing useful clues, and sending signals to threads about to be destroyed could cause resource release timing issues. The fourth layer of filtering attempts to extract the kernel lightweight process ID from the pre-stored fields of the thread metadata structure through the thread information query interface. If the value of this field is zero or invalid (e.g., some special placeholder threads not bound to a kernel scheduling entity), the thread is determined to be unlocatable and skipped directly.
[0036] After passing through the above four layers of filtering, the remaining threads are marked as target threads. At this point, the dedicated signal handling thread safely reads the pre-stored kernel lightweight process ID (LWP ID) from the target thread's metadata structure. This lightweight process ID is obtained through system calls (such as clone or gettid) and cached in the metadata when the thread is created, avoiding the additional overhead and uncertainty caused by dynamic lookup in the signal handling context. After obtaining a valid lightweight process ID, the broadcast operation enters the final delivery stage: the dedicated signal handling thread calls the kernel-level thread signal delivery system call (such as tgkill) provided by the operating system, using the process identifier (PID) of the current database process and the lightweight process ID (LWP ID) of the target thread as two parameters. Unlike the traditional kill based only on the process identifier or pthread_kill based only on the thread identifier, tgkill requires both the process ID and the thread ID to be specified, ensuring that the signal is accurately delivered to a specific thread within the same process, completely avoiding the risk of misdelivery caused by the assumption of global uniqueness of thread IDs within a process.
[0037] Throughout the broadcast process, the dedicated signal processing thread immediately continues to traverse the next target thread after each acquisition signal is delivered, without waiting for the target thread to complete its acquisition or checking its response status. This "fire and forget" design ensures that the execution time of the broadcast operation is linearly related to the total number of threads with a very small coefficient. More importantly, since all operations in the broadcast phase are executed after the mutex is previously released, the signal processing thread does not hold any locks during the entire traversal and delivery process. Therefore, when the target thread receives the second acquisition signal and enters the interrupt service function, it can immediately compete for and acquire the mutex for writing stack information without waiting for the broadcast thread to release resources. This effectively eliminates the latency of cross-thread lock contention and optimizes the concurrent write performance of the entire system.
[0038] In one embodiment, S400 includes: When the target thread receives the second acquisition signal, it checks the pending signal queue at the current instruction boundary of the target thread and interrupts the current execution flow of the target thread; Allocate a signal context structure on the user-mode stack of the target thread, and save the register context data, signal number, and process identifier of the signal sender of the target thread into the signal context structure; Set the instruction pointer to the entry address of the interrupt service function in the saved register context data; Switch the execution state of the target thread from kernel mode to user mode.
[0039] In this embodiment, when the target thread receives the second acquisition signal, the operating system's kernel signal handling mechanism intervenes. This process does not begin with an immediate interruption of the signal, but rather at the current instruction boundary of the target thread—that is, the brief interval between the completion of each machine instruction and the start of the next instruction—the kernel checks the thread's pending signal queue. If the second acquisition signal is present in the queue, the kernel immediately initiates an interrupt operation on the thread's execution flow. This "instruction boundary" checking mechanism ensures that the interrupt occurs at a stable point in the program state, rather than in the middle of arbitrary instructions, thus avoiding data structure corruption caused by interrupting atomic operations.
[0040] After an interrupt is triggered, the kernel dynamically allocates a signal context structure on the target thread's user-space stack. This structure is crucial for subsequent execution resumption. The kernel saves the target thread's complete register context data at the current moment—including the Instruction Pointer (IP), Stack Pointer (SP), Frame Pointer (FP), and the values of all general-purpose registers (such as rax, rbx, rcx, etc.)—into this structure. Simultaneously, the signal number (i.e., the value of the second acquired signal) and the sender's process ID are also stored in this structure. This allows the interrupt service routine to determine the signal's source (internal broadcast or external process) and decide the output target (uniform log file or standard error output). This saving operation is essentially a "snapshot freeze" of the thread's execution state, ensuring that the state before the interrupt is completely preserved regardless of what operations the subsequent interrupt handler performs.
[0041] After saving the register context, the kernel begins making critical modifications to the saved data to guide the thread into the interrupt service routine. Specifically, the kernel modifies the instruction pointer field in the signal context structure to the entry address (i.e., the function's starting address in memory) of the pre-registered second signal acquisition interrupt service routine; simultaneously, it adjusts the stack pointer to point to the reserved stack space above the signal context structure for the interrupt service routine. It's worth noting that registers such as the frame pointer are not modified at this stage, awaiting reset by the interrupt service routine itself according to its calling convention. Furthermore, the kernel marks attributes such as automatic slow system call restart (SA_RESTART) in the context structure based on flags set during registration, ensuring correct execution during the subsequent recovery phase.
[0042] Once all contexts are ready, the kernel switches the target thread's execution state from kernel mode to user mode. This switch is accomplished through the operating system's standard user-mode return path. As a result, when the target thread regains a CPU time slice, its instruction pointer already points to the entry point of the interrupt service routine, and the stack pointer has been adjusted to the newly allocated stack frame area. The thread then begins executing the interrupt service routine from user mode. From an external perspective, the target thread appears to have "voluntarily" called this function, but in reality, the entire process is transparently completed by the kernel during signal delivery, and the interrupted business code is completely unaware. Throughout this operation, the kernel does not use any process tracing (ptrace) or stop signals; the target thread never enters a paused state. Instead, it achieves "soft interrupt" injection for stack sampling through instruction stream redirection, ensuring timely sampling while avoiding the destructive impact of traditional debugging methods on the thread's execution state.
[0043] In one embodiment, S600 includes: When the interrupt service function is executed, the asynchronous signal safe format output module is invoked; The asynchronous signal safe format output module allocates a format buffer on the stack frame of the interrupt service function; The formatting operation with zero library function dependencies is performed using integer conversion algorithm and pointer conversion algorithm, and the formatting result is written to the formatting buffer; The formatting result of the formatting buffer is output to the file descriptor of the unified log file by writing a system call; Based on the frame pointer register, a linked list traversal is performed. The return address and the previous frame pointer in each stack frame are read sequentially from the current frame pointer address. The linked list traversal is iterated until the frame pointer is null or the backtracking depth reaches the preset traversal limit to obtain the thread stack information. After completing the stack backtracking operation, the mutex lock is reacquired, and the unified log file is opened in append mode under the protection of the mutex lock to obtain the file descriptor; Based on the file descriptor, the thread identifier, lightweight process ID, stack bottom pointer, stack space size, thread stack information, and currently executed database operation statement of the target thread are written into the unified log file. After writing is completed, the unified log file is closed and the mutex lock is released.
[0044] In this embodiment, after the kernel redirects the target thread's instruction pointer to the interrupt service function entry point for the second signal acquisition, the central processing unit (CPU) begins executing the function in user mode. Because this function runs in a signal interrupt context, its callable system interfaces are strictly limited by the operating system's whitelist of async-signal-safe functions—any call involving heap memory allocation (such as malloc), standard input / output buffering (such as printf), or global state modification (such as complex time functions other than gettimeofday) may lead to deadlock or data corruption. Therefore, the first action of the interrupt service function is to call a specially designed Async-Signal-Safe Formatting Module, which is the core foundation for the reliable execution of the entire stack acquisition process.
[0045] The asynchronous signal safe formatted output module is designed according to the "three zeros" principle: zero heap allocation, zero library calls, and zero global state. When called, it first allocates a fixed-size formatted buffer (usually several KB) on the current stack frame of the interrupt service function. This buffer is a local variable, located in the thread's own user-mode stack, and is entirely managed by the stack pointer. It does not involve any heap memory operations, thus avoiding lock contention within the memory allocator and eliminating concerns about memory leaks. Subsequently, the module's integer and pointer conversion algorithms begin to work—all of which are implemented by the module itself. For example, when converting an unsigned integer to a decimal character array, it uses an iterative method of repeatedly dividing by 10 and filling in reverse order, rather than relying on the standard library's snprintf; when converting a pointer address to a hexadecimal string, it uses bitwise operations to map half a byte to the characters 0-9a-f. These algorithms do not call any library functions (such as strlen, memcpy, etc.) throughout the entire process, nor do they use global error codes (errno) or locale settings, thus completely avoiding the asynchronous signal safety risks caused by non-reentrant library functions or reliance on global state. After formatting each field (such as thread ID, stack address, return address, etc.), the module writes the result string continuously to the stack buffer, and performs a boundary check before each write to ensure that the buffer capacity is not overflowed. If the space is insufficient, it is truncated and marked, eliminating the risk of stack overflow attacks or crashes.
[0046] After the formatted buffer is filled, the module directly calls the operating system's write system call (such as `write`) to output the contents of the buffer to the target file descriptor. It's important to emphasize that the output destination here depends on the signal source – if the interrupt service routine identifies the signal as originating from within its own process (i.e., broadcast by a dedicated signal handling thread) through the sender process identifier in the signal context structure, it writes to the unified log file; if it identifies the signal as being sent by an external process, it falls back to standard error output (file descriptor 2). Regardless of the output path, the write operation uses system call primitives, bypassing all user-mode buffering layers to ensure the atomicity and safety of the operation.
[0047] While formatting the output, the interrupt service routine also needs to perform the most critical operation—stack backtracking. The backtracking algorithm is based on a linked list of call chains maintained by the CPU's Frame Pointer Register (rbp or ebp). The principle is as follows: under most compiler optimization levels, each function entry point pushes the frame pointer of its caller (the parent function) onto the stack, and then stores the current stack top address in the frame pointer register, forming a linked list of frame pointers. The backtracking algorithm iterates from the current frame pointer address: first, it reads the memory value 8 bytes off the frame pointer (on a 64-bit system), which is the return address that the current function should return after execution; this address is recorded as one level of the call stack. Then, it reads the memory value pointed to by the frame pointer, which is the frame pointer address of the parent function; the parent frame pointer is assigned to the loop variable, and the next iteration continues. The loop continues until the frame pointer becomes null (usually 0) or the backtracking depth reaches the preset traversal limit (e.g., 128 levels), thus obtaining the complete sequence of call stack frame addresses from the innermost to the outermost layer of the current thread. In a signal interruption scenario, the top of this call stack contains the frame of the interrupt service function itself, followed by the kernel's signal trampoline, and then the complete call chain of the interrupted business code. Since the kernel has saved the frame pointer value at the time of interruption, the backtracking algorithm can correctly traverse this boundary and obtain accurate business layer stack information.
[0048] After completing the stack backtracking operation and obtaining all frame addresses, the interrupt service routine (ESR) needs to persist this diagnostic information to a unified log file. At this point, it reacquires the mutex used in the centralized preparation phase to ensure serialization during concurrent writes by multiple threads. After acquiring the lock, it opens the unified log file created in the first phase in append mode (O_APPEND) and obtains the file descriptor. Append mode guarantees that regardless of the order in which threads acquire the lock, each written data is appended to the end of the file, preventing overwriting of existing content. Subsequently, the ESR sequentially formats and writes the following diagnostic fields: the target thread's user-mode thread identifier (such as the thread number or name assigned internally by the database), the kernel lightweight process ID (LWP ID), the current stack bottom pointer address, the total stack size, a complete list of call stack frame addresses obtained from the backtracking (with symbolic function names, if available), and the currently executing database operation statement (such as Structured Query Language (SQL) text, truncated to 1 megabyte to prevent excessive space consumption by a single thread). In addition, it includes business semantic information such as the database connection identifier and the thread's kill status. All of these fields are processed through the aforementioned asynchronous signal-secure formatted output module, ensuring absolute safety during the write process.
[0049] Once all diagnostic information is completely written to the file, the interrupt service routine proactively invokes the file close system call to close the file descriptor, ensuring data is written to disk and releasing kernel resources, and then releases the mutex lock. At this point, the stack trace acquisition and output for a single target thread is complete. Subsequently, the function executes a return instruction, triggering the operating system's signal recovery process, restoring the thread to its execution state before the interruption. Throughout this process, the interrupt service routine does not attempt to acquire any business locks (such as storage engine index locks or table locks) nor modify any shared memory data. Therefore, it does not change the lock state or data consistency of the business logic, minimizing the impact on the target thread's operation—a complete acquisition takes only tens of microseconds to a few milliseconds, equivalent to a lightweight function call overhead.
[0050] In one embodiment, S700 includes: When the interrupt service function completes execution and executes the return instruction, a signal recovery system call is triggered; In response to a signal recovery system call, read the register values from the signal context structure at the time the interrupt occurred; The register value is restored to the register of the target thread, and the instruction pointer is restored to the address of the next instruction after the interrupted position. Based on the slow system call auto-restart flag, the slow system call interrupted by the second acquisition signal will be automatically retried after the target thread resumes execution.
[0051] In this embodiment, after the interrupt service function completes all stack capture and output operations, the return instruction (such as `ret`) at the end of the function is triggered. At this time, because this function is a special entry point driven by signal interrupts, its return behavior is not like a normal function that directly jumps back to the caller. Instead, it triggers the operating system's signal recovery system call (usually `sigreturn`). This system call is a dedicated return path designed by the kernel for signal handling, and its function is to completely restore the thread from the "temporary context" of signal handling to its normal execution state before the interruption.
[0052] In response to the signal recovery system call, the kernel immediately accesses the previously saved signal context structure. This structure, located on the target thread's user-mode stack, contains snapshot values of all registers at the moment the interrupt occurred, including the instruction pointer (IP), stack pointer (SP), frame pointer (FP), and the raw data of all general-purpose registers. The kernel sequentially reads these register values from this structure and writes them back to the corresponding hardware registers of the target thread, thus completely reconstructing the complete execution context at the moment the interrupt occurred. Crucially, the instruction pointer is set to the address of the next instruction after the interrupted location—that is, the address after the machine instruction being executed at the time of the interrupt. This address is also stored in the signal context structure. After this setting, when the thread resumes user-mode execution, it continues fetching instructions from this address as if the signal interrupt had never occurred, ensuring complete logical continuity of the business logic.
[0053] In addition to register recovery, the signal recovery system call also checks the flag attributes set during signal handler registration, particularly the slow system call auto-restart flag (SA_RESTART). This flag's function is as follows: if the target thread is executing a potentially blocking slow system call (e.g., reading data from a socket, waiting for a file lock (fcntl), or executing a network accept) before being interrupted by the second acquisition signal, the system call will typically be prematurely terminated by the kernel when the signal interruption occurs, returning error code -1 and setting the global error variable (errno) to EINTR (indicating signal interruption). However, since the SA_RESTART flag is explicitly set during interrupt service function registration, the kernel automatically checks whether the interrupted system call supports restarting after the signal recovery system call completes and before returning control to user space. If it does, the kernel will re-initiate the slow system call, allowing it to resume execution from its initial state, instead of returning an EINTR error to the user-space code. In this way, the system call results perceived by the business thread after execution resumes are exactly the same as when it was not interrupted—either it completes successfully or it fails due to other normal errors, but it will never receive the exception return code "interrupted by signal". This avoids the complex logic of the application layer having to manually retry, and ensures the transparency and robustness of the database core I / O and communication operations.
[0054] Finally, once all registers have been restored and (if necessary) the slow system call is automatically re-initiated, the kernel completes the entire process of the signal recovery system call, switching the target thread's execution state from kernel mode back to user mode. The thread resumes execution from the instruction address before the interrupt. If it was previously in a slow system call, the system call is automatically retried and transitions from a waiting state to a running state; if it was previously executing a normal computation instruction, subsequent logic is seamlessly integrated. Throughout the entire process, the thread never enters a paused state, nor does it release or acquire any business locks. Lock states and data structure consistency remain unaffected, reflecting the core design goal of minimal intrusion into business processes under the "soft interrupt" protocol.
[0055] In one embodiment, a database-based thread stack information acquisition device is provided, which corresponds one-to-one with the database-based thread stack information acquisition method described in the above embodiments. (Refer to...) Figure 3 , Figure 3 This is a schematic diagram of the functional modules of a preferred embodiment of the database-based thread stack information acquisition device of the present invention. The modules include an external trigger module 10, a centralized preparation module 20, a traversal broadcast module 30, a process interruption module 40, a function execution module 50, a stack backtracking module 60, and a process recovery module 70. Detailed descriptions of each functional module are as follows: External trigger module 10 is used to receive the first trigger signal by a dedicated signal processing thread; The centralized preparation module 20 is used to respond to the first trigger signal, and the dedicated signal processing thread creates a unified log file based on the current timestamp and writes the metadata header into the unified log file under the protection of the mutex lock. After completing the writing operation, the unified log file is closed and the mutex lock is released. The broadcast module 30 is used to traverse each thread in the global thread manager through the dedicated signal processing thread after the mutex is released, obtain the lightweight process ID of each thread, and send the second acquisition signal to the target thread with the lightweight process ID as the addressing parameter. The process interrupt module 40 is used to interrupt the current execution flow of the target thread at the instruction boundary when the target thread receives the second acquisition signal, save the register context on the user-mode stack of the target thread and set the instruction pointer to the entry address of the interrupt service function, and switch the target thread from kernel mode to user mode. Function execution module 50 is used in the user mode for the central processing unit to execute the interrupt service function according to the entry address; The stack backtracking module 60 is used to perform a stack backtracking operation through the interrupt service function, obtain thread stack information, and write the thread stack information into the unified log file under the protection of a mutex lock. The process recovery module 70 is used to restore the execution state of the target thread before the interruption based on the register context after the interrupt service function has been executed.
[0056] In one embodiment, the dual-signal splitting and registration module specifically includes: During the database process startup phase, the first trigger signal is added to the signal mask of each thread to block the delivery of the first trigger signal to each thread; The dedicated signal processing thread receives the first trigger signal through a synchronous waiting method, and triggers the full stack acquisition process after receiving the first trigger signal. Set the second acquisition signal to a signal mask that does not enter each thread, and register the interrupt service function corresponding to the second acquisition signal for each thread; When registering the interrupt service function, set the extended signal information flag and the slow system call auto-restart flag for the interrupt service function.
[0057] In one embodiment, the centralized preparation module 20 includes: The dedicated signal processing thread extracts the directory path from the database's error log directory; A unique filename is generated based on the directory path and the current system timestamp, and a unified log file is created using the unique filename. The dedicated signal processing thread opens the unified log file in a preset write mode and writes the timestamp of the trigger time and the database version number as the metadata header into the unified log file. After completing the writing operation of the metadata header, close the unified log file and release the mutex lock.
[0058] In one embodiment, traversing the broadcast module 30 includes: When iterating through the threads in the global thread manager, the dedicated signal processing thread performs a filtering operation on each thread in turn. Skip system auxiliary threads, dedicated signal handling threads, connection threads that are idle or about to be closed, and threads whose valid lightweight process IDs cannot be obtained from the thread metadata structure to obtain the target thread; The target thread is analyzed, and a lightweight process ID is obtained from the target thread's metadata structure. The second acquisition signal is sent to the target thread using the process identifier of the current database process and the lightweight process number as two parameters.
[0059] In one embodiment, the process interruption module 40 includes: When the target thread receives the second acquisition signal, it checks the pending signal queue at the current instruction boundary of the target thread and interrupts the current execution flow of the target thread; Allocate a signal context structure on the user-mode stack of the target thread, and save the register context data, signal number, and process identifier of the signal sender of the target thread into the signal context structure; Set the instruction pointer to the entry address of the interrupt service function in the saved register context data; Switch the execution state of the target thread from kernel mode to user mode.
[0060] In one embodiment, the stack backtrace module 60 includes: When the interrupt service function is executed, the asynchronous signal safe format output module is invoked; The asynchronous signal safe format output module allocates a format buffer on the stack frame of the interrupt service function; The formatting operation with zero library function dependencies is performed using integer conversion algorithm and pointer conversion algorithm, and the formatting result is written to the formatting buffer; The formatting result of the formatting buffer is output to the file descriptor of the unified log file by writing a system call; Based on the frame pointer register, a linked list traversal is performed. The return address and the previous frame pointer in each stack frame are read sequentially from the current frame pointer address. The linked list traversal is iterated until the frame pointer is null or the backtracking depth reaches the preset traversal limit to obtain the thread stack information. After completing the stack backtracking operation, the mutex lock is reacquired, and the unified log file is opened in append mode under the protection of the mutex lock to obtain the file descriptor; Based on the file descriptor, the thread identifier, lightweight process ID, stack bottom pointer, stack space size, thread stack information, and currently executed database operation statement of the target thread are written into the unified log file. After writing is completed, the unified log file is closed and the mutex lock is released.
[0061] In one embodiment, the process recovery module 70 includes: When the interrupt service function completes execution and executes the return instruction, a signal recovery system call is triggered; In response to a signal recovery system call, read the register values from the signal context structure at the time the interrupt occurred; The register value is restored to the register of the target thread, and the instruction pointer is restored to the address of the next instruction after the interrupted position. Based on the slow system call auto-restart flag, the slow system call interrupted by the second acquisition signal will be automatically retried after the target thread resumes execution.
[0062] Specific limitations regarding the database-based thread stack information acquisition device can be found in the aforementioned limitations of the database-based thread stack information acquisition method, and will not be repeated here. Each module in the aforementioned database-based thread stack information acquisition device can be implemented entirely or partially through software, hardware, or a combination thereof. These modules can be embedded in or independent of the processor in the computer device in hardware form, or stored in the memory of the computer device in software form, so that the processor can call and execute the corresponding operations of each module.
[0063] In one embodiment, a computer device is provided, which may be a server, and its internal structure diagram may be as follows: Figure 4As shown, the computer device includes a processor, memory, network interface, and database connected via a system bus. The processor provides determination and control capabilities. The memory includes non-volatile and / or volatile storage media and internal memory. The non-volatile storage media stores the operating system, computer programs, and database. The internal memory provides an environment for the operation of the operating system and computer programs stored in the non-volatile storage media. The network interface is used to communicate with external clients via a network connection. When the computer program is executed by the processor, it implements the functions or steps of a database-based thread stack information acquisition method on the server side.
[0064] In one embodiment, a computer device is provided, which may be a client, and its internal structure diagram may be as follows: Figure 5 As shown, the computer device includes a processor, memory, network interface, display screen, and input devices connected via a system bus. The processor provides determination and control capabilities. The memory includes non-volatile storage media and internal memory. The non-volatile storage media stores the operating system and computer programs. The internal memory provides an environment for the operation of the operating system and computer programs stored in the non-volatile storage media. The network interface is used to communicate with an external server via a network connection. When executed by the processor, the computer program implements client-side functions or steps of a database-based thread stack information acquisition method.
[0065] In one embodiment, a computer device is provided, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the computer program to perform the following steps: The first trigger signal is received by a dedicated signal processing thread; In response to the first trigger signal, the dedicated signal processing thread creates a unified log file based on the current timestamp and writes a metadata header into the unified log file under the protection of a mutex lock. After completing the writing operation, the unified log file is closed and the mutex lock is released. After releasing the mutex lock, the dedicated signal processing thread traverses each thread in the global thread manager to obtain the lightweight process ID of each thread, and sends the second acquisition signal to the target thread using the lightweight process ID as the addressing parameter. When the target thread receives the second acquisition signal, it interrupts the current execution flow of the target thread at the instruction boundary, saves the register context on the user-mode stack of the target thread and sets the instruction pointer to the entry address of the interrupt service function, and switches the target thread from kernel mode to user mode; In the user mode, the central processing unit executes the interrupt service function according to the entry address; The interrupt service function performs a stack backtracking operation to obtain thread stack information, and under the protection of a mutex lock, writes the thread stack information into the unified log file. After the interrupt service function is completed, the execution state of the target thread before the interrupt is restored based on the register context.
[0066] In one embodiment, a computer-readable storage medium is provided, which may be non-volatile or volatile, and a computer program is stored thereon, which, when executed by a processor, performs the following steps: The first trigger signal is received by a dedicated signal processing thread; In response to the first trigger signal, the dedicated signal processing thread creates a unified log file based on the current timestamp and writes a metadata header into the unified log file under the protection of a mutex lock. After completing the writing operation, the unified log file is closed and the mutex lock is released. After releasing the mutex lock, the dedicated signal processing thread traverses each thread in the global thread manager to obtain the lightweight process ID of each thread, and sends the second acquisition signal to the target thread using the lightweight process ID as the addressing parameter. When the target thread receives the second acquisition signal, it interrupts the current execution flow of the target thread at the instruction boundary, saves the register context on the user-mode stack of the target thread and sets the instruction pointer to the entry address of the interrupt service function, and switches the target thread from kernel mode to user mode; In the user mode, the central processing unit executes the interrupt service function according to the entry address; The interrupt service function performs a stack backtracking operation to obtain thread stack information, and under the protection of a mutex lock, writes the thread stack information into the unified log file. After the interrupt service function is completed, the execution state of the target thread before the interrupt is restored based on the register context.
[0067] It should be noted that the functions or steps that can be implemented by the computer-readable storage medium or computer device described above can be referred to the relevant descriptions on the server side and client side in the foregoing method embodiments. To avoid repetition, they will not be described one by one here.
[0068] Those skilled in the art will understand that all or part of the processes in the methods of the above embodiments can be implemented by a computer program instructing related hardware. The computer program can be stored in a non-volatile computer-readable storage medium, and when executed, it can include the processes of the embodiments of the above methods. Any references to memory, storage, databases, or other media used in the embodiments provided in this application can include non-volatile and / or volatile memory. Non-volatile memory can include read-only memory (ROM), programmable ROM (PROM), electrically programmable ROM (EPROM), electrically erasable programmable ROM (EEPROM), or flash memory. Volatile memory can include random access memory (RAM) or external cache memory. By way of illustration and not limitation, RAM is available in various forms, such as static RAM (SRAM), dynamic RAM (DRAM), synchronous DRAM (SDRAM), dual data rate SDRAM (DDRSDRAM), enhanced SDRAM (ESDRAM), synchronous link DRAM (SLDRAM), Rambus direct RAM (RDRAM), direct memory bus dynamic RAM (DRDRAM), and memory bus dynamic RAM (RDRAM), etc.
[0069] Those skilled in the art will clearly understand that, for the sake of convenience and brevity, the above-described division of functional units and modules is used as an example. In practical applications, the above functions can be assigned to different functional units and modules as needed, that is, the internal structure of the device can be divided into different functional units or modules to complete all or part of the functions described above.
[0070] It should be noted that any AI models, software tools, or components not belonging to this company appearing in the embodiments of this application are merely illustrative examples and do not represent actual use. All user personal information involved in the embodiments of this application has been authorized (with the knowledge and consent) by the relevant parties or has been fully authorized by all parties, and the executing entity may obtain it through various legal and compliant means. The collection, storage, use, processing, transmission, provision, and disclosure of the information, data, and signals involved all comply with relevant laws and regulations and do not violate public order and good morals.
[0071] The above-described embodiments are only used to illustrate the technical solutions of the present invention, and are not intended to limit it. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention, and should all be included within the protection scope of the present invention.
Claims
1. A database-based method for collecting thread stack information, characterized in that, Includes the following steps: The first trigger signal is received by a dedicated signal processing thread; In response to the first trigger signal, the dedicated signal processing thread creates a unified log file based on the current timestamp and writes a metadata header into the unified log file under the protection of a mutex lock. After completing the writing operation, the unified log file is closed and the mutex lock is released. After releasing the mutex lock, the dedicated signal processing thread traverses each thread in the global thread manager to obtain the lightweight process ID of each thread, and sends the second acquisition signal to the target thread using the lightweight process ID as the addressing parameter. When the target thread receives the second acquisition signal, it interrupts the current execution flow of the target thread at the instruction boundary, saves the register context on the user-mode stack of the target thread and sets the instruction pointer to the entry address of the interrupt service function, and switches the target thread from kernel mode to user mode; In the user mode, the central processing unit executes the interrupt service function according to the entry address; The interrupt service function performs a stack backtracking operation to obtain thread stack information, and under the protection of a mutex lock, writes the thread stack information into the unified log file. After the interrupt service function is completed, the execution state of the target thread before the interrupt is restored based on the register context.
2. The database-based thread stack information acquisition method as described in claim 1, characterized in that, Before the dedicated signal processing thread receives the first trigger signal, the specific steps include: During the database process startup phase, the first trigger signal is added to the signal mask of each thread to block the delivery of the first trigger signal to each thread; The dedicated signal processing thread receives the first trigger signal through a synchronous waiting method, and triggers the full stack acquisition process after receiving the first trigger signal. Set the second acquisition signal to a signal mask that does not enter each thread, and register the interrupt service function corresponding to the second acquisition signal for each thread; When registering the interrupt service function, set the extended signal information flag and the slow system call auto-restart flag for the interrupt service function.
3. The database-based thread stack information acquisition method as described in claim 1, characterized in that, In response to the first trigger signal, the dedicated signal processing thread, under the protection of a mutex lock, creates a unified log file based on the current timestamp and writes metadata headers into the unified log file. After completing the write operation, it closes the unified log file and releases the mutex lock, including: The dedicated signal processing thread extracts the directory path from the database's error log directory; A unique filename is generated based on the directory path and the current system timestamp, and a unified log file is created using the unique filename. The dedicated signal processing thread opens the unified log file in a preset write mode and writes the timestamp of the trigger time and the database version number as the metadata header into the unified log file. After completing the writing operation of the metadata header, close the unified log file and release the mutex lock.
4. The database-based thread stack information acquisition method as described in claim 1, characterized in that, After releasing the mutex lock, the dedicated signal processing thread iterates through each thread in the global thread manager to obtain the lightweight process ID of each thread, and sends a second acquisition signal to the target thread using the lightweight process ID as the addressing parameter, including: When iterating through the threads in the global thread manager, the dedicated signal processing thread performs a filtering operation on each thread in turn. Skip system auxiliary threads, dedicated signal handling threads, connection threads that are idle or about to be closed, and threads whose valid lightweight process IDs cannot be obtained from the thread metadata structure to obtain the target thread; The target thread is analyzed, and a lightweight process ID is obtained from the target thread's metadata structure. The second acquisition signal is sent to the target thread using the process identifier of the current database process and the lightweight process number as two parameters.
5. The database-based thread stack information acquisition method as described in claim 1, characterized in that, When the target thread receives the second acquisition signal, it interrupts its current execution flow at the instruction boundary, saves the register context on the target thread's user-mode stack, sets the instruction pointer to the entry address of the interrupt service function, and returns the target thread from kernel mode to user mode, including: When the target thread receives the second acquisition signal, it checks the pending signal queue at the current instruction boundary of the target thread and interrupts the current execution flow of the target thread; Allocate a signal context structure on the user-mode stack of the target thread, and save the register context data, signal number, and process identifier of the signal sender of the target thread into the signal context structure; Set the instruction pointer to the entry address of the interrupt service function in the saved register context data; Switch the execution state of the target thread from kernel mode to user mode.
6. The database-based thread stack information acquisition method as described in claim 1, characterized in that, The interrupt service function performs a stack backtracking operation to obtain thread stack information, and under the protection of a mutex lock, writes the thread stack information to the unified log file, including: When the interrupt service function is executed, the asynchronous signal safe format output module is invoked; The asynchronous signal safe format output module allocates a format buffer on the stack frame of the interrupt service function; The formatting operation with zero library function dependencies is performed using integer conversion algorithm and pointer conversion algorithm, and the formatting result is written to the formatting buffer; The formatting result of the formatting buffer is output to the file descriptor of the unified log file by writing a system call; Based on the frame pointer register, a linked list traversal is performed. The return address and the previous frame pointer in each stack frame are read sequentially from the current frame pointer address. The linked list traversal is iterated until the frame pointer is null or the backtracking depth reaches the preset traversal limit to obtain the thread stack information. After completing the stack backtracking operation, the mutex lock is reacquired, and the unified log file is opened in append mode under the protection of the mutex lock to obtain the file descriptor; Based on the file descriptor, the thread identifier, lightweight process ID, stack bottom pointer, stack space size, thread stack information, and currently executed database operation statement of the target thread are written into the unified log file. After writing is completed, the unified log file is closed and the mutex lock is released.
7. The database-based thread stack information acquisition method as described in claim 1, characterized in that, After the interrupt service function completes execution, the execution state of the target thread before the interrupt is restored based on the register context, including: When the interrupt service function completes execution and executes the return instruction, a signal recovery system call is triggered; In response to a signal recovery system call, read the register values from the signal context structure at the time the interrupt occurred; The register value is restored to the register of the target thread, and the instruction pointer is restored to the address of the next instruction after the interrupted position. Based on the slow system call auto-restart flag, the slow system call interrupted by the second acquisition signal will be automatically retried after the target thread resumes execution.
8. A database-based thread stack information acquisition device, characterized in that, The database-based thread stack information acquisition device includes: An external trigger module is used to receive the first trigger signal by a dedicated signal processing thread; The centralized preparation module is used to respond to the first trigger signal, and the dedicated signal processing thread creates a unified log file based on the current timestamp and writes the metadata header into the unified log file under the protection of a mutex lock. After completing the writing operation, the unified log file is closed and the mutex lock is released. The traversal broadcast module is used to traverse each thread in the global thread manager through the dedicated signal processing thread after the mutex is released, obtain the lightweight process ID of each thread, and send the second acquisition signal to the target thread with the lightweight process ID as the addressing parameter. The process interruption module is used to interrupt the current execution flow of the target thread at the instruction boundary when the target thread receives the second acquisition signal, save the register context on the user-mode stack of the target thread and set the instruction pointer to the entry address of the interrupt service function, and switch the target thread from kernel mode to user mode. The function execution module is used in the user mode for the central processing unit to execute the interrupt service function according to the entry address; The stack backtracking module is used to perform stack backtracking operations through the interrupt service function, obtain thread stack information, and write the thread stack information into the unified log file under the protection of a mutex lock. The process recovery module is used to restore the execution state of the target thread before the interruption based on the register context after the interrupt service function has been executed.
9. A computer device, characterized in that, The computer device includes a memory, a processor, and a database-based thread stack information acquisition program stored in the memory and executable on the processor. When the database-based thread stack information acquisition program is executed by the processor, it implements the steps of the database-based thread stack information acquisition method as described in any one of claims 1-7.
10. A computer-readable storage medium, characterized in that, The storage medium stores a database-based thread stack information acquisition program, which, when executed by a processor, implements the steps of the database-based thread stack information acquisition method as described in any one of claims 1-7.
