A plug-in code execution method and related device in a multi-tenant environment

CN122903065APending Publication Date: 2026-10-13FAN RUAN SOFTWARE CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611127273.1
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-28
Publication Date
2026-10-13

AI Technical Summary

Technical Problem

[0005]鉴于上述问题,本申请提供了一种多租户环境下的插件代码执行方法及相关装置,以解决多租户环境下的插件代码执行的安全性较低的问题

Benefits of technology

[0037]借由上述技术方案,本申请提供的一种多租户环境下的插件代码执行方法及相关装置。该方法包括对插件源代码进行结构分析,根据预设安全规则识别并改写其中的风险代码模式,从而在代码执行前主动消除已知安全隐患,实现了从被动拦截到主动防御的转变;在此基础上,将经过结构分析的代码置于独立的隔离进程中执行,并通过预设配额限制隔离进程的资源使用量,同时在隔离进程中加载配置有预设系统调用白名单的系统调用过滤器,从而使恶意代码与宿主进程之间不存在共享的进程空间和内存空间,隔断了逃逸成功后直接获取宿主进程权限的路径,即使某一层防护被绕过,其他层仍然独立发挥作用,实现了从代码层、进程层到内核层的纵深防御;进一步地,本申请基于目标租户的资源配额对执行请求进行限流,根据通过限流的执行请求确定执行任务,防止单一租户提交大量执行请求挤占其他租户的调度资源。由此,本申请通过结构分析、隔离进程、系统调用过滤和租户级限流的多层次联动,在隔离进程中执行插件安全代码,全面提升了多租户环境下插件代码执行的安全性。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122903065A_ABST
    Figure CN122903065A_ABST
Patent Text Reader

Abstract

The application discloses a plug-in code execution method and related device in a multi-tenant environment, and relates to the technical field of computer security. The method comprises the following steps: performing structural analysis on plug-in source code, identifying and rewriting risk codes in the plug-in source code according to preset security rules; executing the code subjected to the structural analysis in an independent isolated process, limiting the resource usage of the isolated process through a preset quota, and loading a system call filter configured with a preset system call whitelist in the isolated process; further, the application limits the execution request based on the resource quota of a target tenant, determines an execution task according to the execution request subjected to the limiting, allocates the execution task to the isolated process, executes plug-in security code, and obtains a plug-in code execution result. Therefore, through the multi-level linkage of structural analysis, isolated process, system call filtering and tenant-level limiting, the safety of executing plug-in security code in an isolated process under a multi-tenant environment is comprehensively improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of computer security technology, and in particular to a method and related apparatus for executing plug-in code in a multi-tenant environment. Background Technology

[0002] With the widespread adoption of the Software as a Service (SaaS) model, multi-tenant architecture has become the mainstream form of enterprise software delivery. More and more SaaS platforms are opening up the ability for tenants to customize business logic, allowing them to inject personalized logic into platform processes by uploading plugin code. This openness and scalability significantly enhances the platform's flexibility; therefore, ensuring the secure execution of plugin code in a multi-tenant shared runtime environment is particularly important.

[0003] Currently, in-process sandbox solutions based on language runtimes are widely used. Taking the vm2 library in the Node.js ecosystem as an example, this type of solution creates a virtual execution environment within the same process to proxy and shield dangerous operations, thereby achieving isolated execution of user code.

[0004] However, sandbox solutions cannot proactively identify and eliminate risky code patterns before code execution. Malicious code gains execution opportunities within the sandbox before being intercepted. Furthermore, since the sandbox shares the same operating system process with the host process, if the sandbox itself has implementation defects or logical vulnerabilities, malicious code can exploit these vulnerabilities to escape and run directly within the host process's permission context, accessing all resources owned by the host process. This results in lower security for plugin code execution in a multi-tenant environment. Summary of the Invention

[0005] In view of the above problems, this application provides a method and related apparatus for executing plugin code in a multi-tenant environment to solve the problem of low security in plugin code execution in a multi-tenant environment. The specific solution is as follows:

[0006] The first aspect of this application provides a method for executing plugin code in a multi-tenant environment, including:

[0007] Obtain the plugin source code submitted by the target tenant in a multi-tenant environment, and perform structural analysis on the plugin source code to obtain the plugin security code;

[0008] An isolation process is constructed, and a system call filter configured with a preset system call whitelist is loaded into the isolation process. The amount of resources that the isolation process can use is limited by a preset quota.

[0009] In response to an execution request for the security code of the plugin, the execution request is rate-limited based on the resource quota of the target tenant, and the execution task is determined based on the execution request that passes the rate limit;

[0010] The execution task is assigned to the isolated process, and the plugin security code is executed in the isolated process to obtain the plugin code execution result.

[0011] In one possible implementation, the structural analysis of the plugin source code to obtain plugin security code includes:

[0012] The abstract syntax tree engine is invoked to perform structural parsing on the plugin source code, thereby obtaining the abstract syntax tree of the plugin source code;

[0013] Based on preset security rules, multiple nodes of the abstract syntax tree are traversed, and the code fragments corresponding to the nodes that do not match the preset security rules are identified as risky code fragments in the plugin source code.

[0014] The risky code snippets in the plugin's source code are rewritten to obtain the safe code for the plugin.

[0015] In one possible implementation, the construction process of the isolation process includes:

[0016] Obtain pre-started runtime processes from the preset process pool;

[0017] An independent resource view is created for the runtime process by invoking the namespace mechanism of the operating system kernel;

[0018] The operating system kernel's control group mechanism is invoked to set the preset quotas for the runtime process. The preset quotas include the upper limit of CPU usage and the upper limit of memory usage.

[0019] In one possible implementation, the system call filter is also configured with conditional restriction rules for sensitive system calls;

[0020] The condition restriction rules include: restricting the operation path of open system calls to a preset temporary directory, and / or restricting the connection target of network connection system calls to a preset address whitelist.

[0021] In one possible implementation, before determining the execution task based on the execution request via rate limiting, the method further includes:

[0022] Based on the scenario identifier of the execution request that passed the rate limiting, the execution task corresponding to the execution request that passed the rate limiting is divided into the corresponding scenario queue, and the scheduling priority of the execution task in the scenario queue is determined based on the waiting time of the execution task in the scenario queue.

[0023] The step of determining the execution task based on the execution request through rate limiting includes:

[0024] Based on the scheduling priority of the tasks to be executed in the scenario queue, a target task to be executed is determined from the tasks to be executed in the scenario queue using a task-level scheduling strategy, which includes a shortest job priority strategy or a priority queue strategy.

[0025] In one possible implementation, executing the plugin security code in the isolation process to obtain the plugin code execution result includes:

[0026] Set an execution timeout for the isolation process;

[0027] When the execution time of the plugin security code does not exceed the execution timeout, data interaction is performed with the business platform corresponding to the multi-tenant environment through the security application programming interface to obtain the execution result of the plugin code;

[0028] The isolation process is terminated when the execution time of the plugin security code exceeds the execution timeout period.

[0029] In one possible implementation, after assigning the execution task to the isolated process, executing the plugin security code in the isolated process, and obtaining the plugin code execution result, the method further includes:

[0030] Clear global variables in the isolation process, close network connections in the isolation process, and release memory occupied by the isolation process;

[0031] The isolated process is then returned to the preset process pool after being released.

[0032] A second aspect of this application provides a computer program product including computer-readable instructions that, when executed on an electronic device, cause the electronic device to implement the plug-in code execution method in a multi-tenant environment as described in the first aspect or any implementation thereof.

[0033] A third aspect of this application provides an electronic device, comprising at least one processor and a memory connected to the processor, wherein:

[0034] The memory is used to store computer programs;

[0035] The processor is used to execute the computer program so that the electronic device can implement the plug-in code execution method in a multi-tenant environment in accordance with the first aspect or any implementation thereof.

[0036] The fourth aspect of this application provides a computer storage medium carrying one or more computer programs, which, when executed by an electronic device, enable the electronic device to implement the plug-in code execution method in a multi-tenant environment as described in the first aspect or any implementation thereof.

[0037] Based on the above technical solution, this application provides a method and related apparatus for plugin code execution in a multi-tenant environment. The method includes structural analysis of the plugin source code, identifying and rewriting risky code patterns according to preset security rules, thereby proactively eliminating known security vulnerabilities before code execution and achieving a shift from passive interception to proactive defense. Furthermore, the structurally analyzed code is executed in an independent isolated process, and the resource usage of the isolated process is limited by preset quotas. Simultaneously, a system call filter with a preset system call whitelist is loaded into the isolated process, ensuring that malicious code and the host process do not share process space and memory space, thus cutting off the path for successfully escaping and directly obtaining host process privileges. Even if one layer of protection is bypassed, other layers still function independently, achieving in-depth defense from the code layer, process layer, to the kernel layer. Further, this application rate-limits execution requests based on the target tenant's resource quota, determining the execution task based on the rate-limited execution requests, preventing a single tenant from submitting a large number of execution requests and crowding out the scheduling resources of other tenants. Therefore, this application comprehensively improves the security of plugin code execution in a multi-tenant environment by executing plugin security code in an isolated process through multi-layered linkage of structural analysis, process isolation, system call filtering, and tenant-level rate limiting. Attached Figure Description

[0038] The above and other features, advantages, and aspects of the embodiments of this disclosure will become more apparent from the accompanying drawings and the following detailed description. Throughout the drawings, the same or similar reference numerals denote the same or similar elements. It should be understood that the drawings are schematic, and the originals and elements are not necessarily drawn to scale.

[0039] Figure 1 A flowchart illustrating a plugin code execution method in a multi-tenant environment, provided as an embodiment of this application;

[0040] Figure 2 This is a schematic diagram of the hardware structure of an electronic device provided in an embodiment of this application. Detailed Implementation

[0041] The embodiments of this application are described below with reference to the accompanying drawings. The terminology used in the implementation section of this application is for explaining specific embodiments only and is not intended to limit the scope of this application.

[0042] The embodiments of this application will now be described with reference to the accompanying drawings. Those skilled in the art will recognize that, with technological advancements and the emergence of new scenarios, the technical solutions provided in the embodiments of this application are equally applicable to similar technical problems.

[0043] The terms "first," "second," etc., used in the specification, claims, and accompanying drawings of this application are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such terms are interchangeable where appropriate; this is merely a way of distinguishing objects with the same attributes in the embodiments of this application. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion, so that a process, method, system, product, or apparatus that comprises a series of elements is not necessarily limited to those elements but may include other elements not explicitly listed or inherent to those processes, methods, products, or apparatuses.

[0044] To improve the security of plugin code execution in a multi-tenant environment, this application provides a plugin code execution method in a multi-tenant environment. The plugin code execution method in a multi-tenant environment provided by this application will be further described in detail below with reference to the accompanying drawings and specific embodiments.

[0045] Example 1:

[0046] Please see Figure 1 , Figure 1 This is a flowchart illustrating a plugin code execution method in a multi-tenant environment, as provided in an embodiment of this application. The method may include the following steps:

[0047] Step S101: Obtain the plugin source code submitted by the target tenant in a multi-tenant environment, and perform structural analysis on the plugin source code to obtain the plugin security code.

[0048] Specifically, plugin source code can refer to custom program code snippets written by tenants in a multi-tenant SaaS platform to extend business logic, typically written in languages ​​such as JavaScript, Python, or Java. The plugin source code can be obtained, for example, by receiving submitted code text through the platform's front-end code editor interface, or by receiving code packages pushed by external development tools through an Application Programming Interface (API).

[0049] Structural analysis of the plugin's source code aims to identify and remove potential security risks through static code auditing. This analysis process involves, for example, using static code scanning tools to traverse the code's abstract syntax tree, checking for dangerous function calls such as file operations, network operations, and system command execution; or employing a rule-based semantic analysis engine to detect specific statement patterns attempting to access sensitive paths in the host environment or try to escape the sandbox. The system then removes or rewrites the identified risky code snippets, generating cleaned, secure plugin code. This static cleaning step, performed before the code is stored in the repository, reduces runtime security risks at the source, providing a foundation for subsequent isolated execution.

[0050] Step S102: Construct an isolation process and load a system call filter with a preset system call whitelist into the isolation process. The amount of resources that the isolation process can use is limited by the preset quota.

[0051] Specifically, an isolation process is an independent runtime environment created at the operating system level to achieve runtime isolation between tenant code and the host system and other tenant code. The process of building an isolation process may involve, for example, calling the operating system kernel's namespace mechanism to create an independent mount point, network protocol stack, and process ID view for the process, making it unaware of or unable to access the host machine's system resources; or generating a lightweight sandbox container instance based on the existing container runtime interface.

[0052] During the build process, a system call filter is loaded into the isolated process. A system call filter is a monitoring mechanism running in kernel or user space that intercepts all system calls initiated by a process and allows only calls that match a predefined system call whitelist to pass. The predefined system call whitelist is a predefined set of allowed system calls; for example, it may only allow non-destructive calls such as memory allocation and basic I / O reads, while prohibiting high-risk calls such as file writes and network creation, thus building a security defense at the kernel level.

[0053] Furthermore, to ensure resource fairness and prevent resource abuse in a multi-tenant environment, the amount of resources available to isolated processes is limited by preset quotas. These preset quotas can be determined in various ways, such as allocating them based on the service package level purchased by the target tenant—for example, allocating higher CPU time slices and memory quotas to gold tenants and lower quotas to silver tenants; or dynamically adjusting them based on the platform's overall resource load, automatically reducing the quota limits for all tenants when resources are scarce. The specific implementation of resource limits includes, for example, limiting the CPU usage and memory usage limits of processes through the operating system's control group mechanism. Once a process attempts to exceed these quotas, the kernel will restrict its resource acquisition or directly trigger a limiting action. This dual-limiting mechanism ensures that plugin code runs in a controlled sandbox environment, preventing it from damaging the system through illegal system calls or affecting other tenants by exhausting resources.

[0054] Step S103: In response to the execution request for the plugin security code, the execution request is rate-limited based on the target tenant's resource quota, and the execution task is determined based on the execution request that passes the rate limit.

[0055] Specifically, an execution request can refer to a business instruction triggered by an external business system or user to run a plugin. It typically carries a plugin identifier, input parameters, and the target tenant's identity information. In response to this request, the system first performs tenant-based flow control, i.e., rate limiting, to prevent a single tenant from exhausting system computing resources due to submitting too many requests, leading to service rejection or affecting the service quality of other tenants. Rate limiting of execution requests is based on the target tenant's resource quota. For example, a token bucket algorithm can be used, maintaining a token bucket for each tenant, with the token generation rate proportional to the tenant's resource quota; a request is only allowed to pass when it acquires a token. Alternatively, a leaky bucket algorithm or a fixed window counter can be used to count the number of requests from the tenant per unit time; when the number exceeds a preset quota threshold, subsequent requests are directly rejected.

[0056] For execution requests that pass rate limiting, the system transforms them into specific execution tasks. The process of determining the execution task includes parsing the parameters in the request and encapsulating them into a standard task object that can be processed by the scheduler. This task object may contain information such as the storage address of the plugin code, runtime parameters, callback notification address, and task priority. Through the rate limiting mechanism, the system ensures that the number of tasks entering the scheduling queue is within the system's capacity, thereby guaranteeing the stability and efficiency of subsequent processing.

[0057] Step S104: Assign the execution task to the isolated process, execute the plugin security code in the isolated process, and obtain the plugin code execution result.

[0058] Specifically, assigning tasks to isolated processes can refer to the scheduler delivering tasks to the prepared isolated runtime environment according to a preset scheduling policy. The assignment process may involve using remote procedure calls or inter-process communication mechanisms to send task data to the main loop of the isolated process; or writing tasks to a shared memory queue for the isolated process to actively retrieve. Executing safe plugin code within the isolated process can refer to the interpreter or runtime engine within the process loading and running cleaned code logic. During execution, the code is confined to the isolated environment, can only access limited resources, and all system calls must be validated by the aforementioned system call filter.

[0059] The result of code execution, i.e., the result of plugin code execution, can be a calculated data return value, a confirmation status of successful operation, or captured runtime exception information. The process of obtaining the plugin code execution result includes, for example, the engine capturing the code's standard output stream and serializing it into JSON formatted response data; or writing the result directly to the business system's database through a pre-defined security callback interface. By executing code in an isolated environment, the system ensures that even if there are logical errors or malicious behavior within the plugin code, it will not affect the data security of the host environment or other tenants, achieving secure isolated execution.

[0060] The aforementioned technical solution eliminates explicit risks during the static code analysis phase and constructs a deep security defense system by combining operating system-level process isolation and system call filtering mechanisms. Simultaneously, it effectively solves resource contention issues in multi-tenant environments through tenant resource quota limits and request rate limiting. This synergistic effect, from code source control and runtime environment isolation to resource scheduling management, enables the multi-tenant SaaS platform to efficiently and stably execute user-defined plugin logic while ensuring high security, achieving a balance between security and performance.

[0061] Example 2:

[0062] In another embodiment, a method for obtaining safe plugin code by performing structural analysis on the plugin source code is provided in a plugin code execution method in a multi-tenant environment according to an embodiment of this application.

[0063] Step S201: Call the abstract syntax tree engine to perform structural parsing on the plugin source code and obtain the abstract syntax tree of the plugin source code.

[0064] Specifically, by introducing a static code analysis mechanism, preprocessing is performed on the code before it enters the runtime environment. An abstract syntax tree (AST) engine is used as the core parsing component to convert the text-based plugin source code submitted by developers into structured data that computers can understand. This parsing process is based on the syntax rules of programming languages ​​(such as JavaScript and Python), decomposing the source code sequence into a token stream and constructing a hierarchical tree-like data structure, namely the Abstract Syntax Tree (AST), according to the syntax rules. Each node in this tree structure corresponds to a syntactic construct in the source code, such as a function declaration, variable assignment, conditional statement, or function call expression, thus fully preserving the logical structure and semantic information of the code.

[0065] Abstract syntax tree (AST) engines can be implemented based on existing mature compiler front-end tools (such as Esprima and Acorn for JavaScript, or AST modules for Python), or they can be parsers custom-developed to meet specific sandbox security requirements. The parsed AST is stored as an in-memory object structure or intermediate representation, providing a traversable and manipulable data foundation for subsequent security checks. By transforming unstructured or semi-structured source code into a standardized AST, subsequent security rule matching can be precise down to the syntactic unit level of the code, avoiding the limitations of relying on easily bypassed text keyword matching.

[0066] Step S202: Traverse multiple nodes of the abstract syntax tree based on preset security rules, and identify the code fragments corresponding to nodes that do not match the preset security rules as risky code fragments in the plugin source code.

[0067] Specifically, after obtaining the abstract syntax tree, a deep security scan is performed, using preset security rules to verify each node of the abstract syntax tree one by one. The preset security rules are a set of judgment logic built based on the principle of least privilege and the constraints of the security sandbox runtime environment. They define the scope of syntax constructions that plugin code is allowed to use and the global objects or function interfaces that are prohibited from access.

[0068] A depth-first search or breadth-first search algorithm is used to access every node in the abstract syntax tree. For each node, its type, name, and attribute information are compared with preset security rules. For example, the preset security rules include a list of prohibited dangerous functions (such as `eval`, the `Function` constructor) and a list of prohibited sensitive objects (such as the `process` object, and `require / import` module loading functions in the global scope). When a node is detected as a call expression and the called function name exists in the list of dangerous functions, or a node is an identifier and references a sensitive global object, the node is determined not to match the preset security rules. For nodes that do not match the rules, their corresponding source code location information and code content are marked and extracted to form a set of risky code fragments. Through this structured analysis based on the syntax tree, it is possible to effectively identify disguised malicious code (such as `eval` calls constructed by string concatenation), which has higher accuracy and resistance to bypass compared to regular expression matching.

[0069] Step S203: Rewrite the risky code snippets in the plugin source code to obtain the safe code for the plugin.

[0070] Specifically, after identifying risky code snippets, code cleaning and rewriting are performed to eliminate potential security vulnerabilities. This process does not simply involve deleting or rejecting the entire plugin containing the risky snippets, but rather using fine-grained code transformation to replace the risky operations with implementations that conform to security standards, thereby ensuring code security while preserving business logic.

[0071] The specific code rewriting varies depending on the type of risk. For risky code snippets involving illegal module imports (such as attempts to import the fs file system module), they are rewritten to throw an exception, blocking the loading process. For risky snippets attempting to execute dynamic code by calling the `eval` function, they are replaced with an empty function or a function returning a fixed safe value. For code involving access to sensitive object properties, it is redirected to a restricted proxy object provided by the sandbox environment. This rewriting process is implemented by manipulating the abstract syntax tree (AST), directly deleting or replacing specific nodes in the tree structure, and then regenerating the modified AST into a new source code string. Through logical refactoring at the AST level, the resulting safe plugin code semantically removes all operations that violate preset security rules, enabling it to run safely in subsequent isolated execution environments without relying on runtime trial-and-error mechanisms, fundamentally reducing the risk of code escape.

[0072] Example 3:

[0073] In another embodiment, a method for constructing an isolated process is provided in a plug-in code execution method in a multi-tenant environment according to an embodiment of this application.

[0074] Step S301: Obtain pre-started runtime processes from the preset process pool.

[0075] Specifically, the pre-defined process pool is a collection of process resource caches created and maintained in advance during system initialization. It internally stores multiple runtime process instances that are ready and have completed basic environment initialization. These runtime processes can be, for example, pre-started Node.js or Python interpreter processes. During creation, the runtime environment is loaded and global objects are initialized, thus avoiding the cold start latency caused by temporarily forking processes or starting virtual machines when a task arrives. The pre-defined process pool generates processes in batches by calling low-level system interfaces (such as Linux's clone system call) and manages them using data structures such as circular linked lists or lock-free queues, enabling the scheduler to quickly acquire idle runtime processes within O1 time complexity. When an isolated process needs to be built, a runtime process is directly retrieved from this pre-defined process pool instead of being created from scratch, thereby reducing startup latency to the millisecond level (e.g., within 10 milliseconds). Although the obtained runtime process physically exists in the host operating system, it will subsequently be given independent isolation attributes.

[0076] Step S302: Create an independent resource view for the runtime process by calling the namespace mechanism of the operating system kernel.

[0077] Specifically, the namespace mechanism is a lightweight resource isolation technology provided by the Linux operating system kernel. It allows a set of system resources to be packaged, giving processes in different namespaces an independent view of those resources. By calling the operating system kernel's namespace-related interfaces (such as the unshare or clone system call in conjunction with flags like CLONE_NEWPID, CLONE_NEWNET, and CLONE_NEWNS), an isolation boundary is constructed for the runtime process obtained in the preceding steps. Specifically, a new PID namespace can be created for the runtime process, making its process ID 1 in the internal view, thus preventing it from being aware of or manipulating processes on the host machine or other tenants; a Network namespace can be created, configuring an independent network protocol stack, routing table, and firewall rules for the process, giving it a network environment isolated from the host machine; a Mount namespace can be created, mounting an independent file system view for the process and redirecting its root directory to a specified isolated directory. After these operations, the runtime process obtains a logically completely independent operating system view, as if it were running on a separate physical machine, but in reality, it shares the host kernel, thus achieving a lightweight isolation effect.

[0078] Step S303: Set preset quotas for runtime processes by calling the control group mechanism of the operating system kernel. The preset quotas include the upper limit of CPU usage and the upper limit of memory usage.

[0079] Specifically, the control group mechanism is a framework in the Linux kernel used to limit, record, and isolate the physical resources used by process groups. After creating an independent resource view, the control group mechanism further imposes hard constraints on the resource usage of runtime processes to prevent plugin code from excessively consuming system resources due to coding errors or malicious logic, thereby affecting the service quality of other tenants. Preset quotas are a set of pre-configured resource usage threshold parameters, which can be determined by factors such as the tenant's purchased service plan, the system's current total load capacity, and the physical limits of the hardware. The acquired runtime processes are added to a specific control group, and specific resource limits are set by writing parameter values ​​to the virtual file system corresponding to the control group (such as configuration files for relevant subsystems under the ` / sys / fs / cgroup / ` directory).

[0080] Specifically, the CPU utilization limit can be set by configuring the CPU subsystem (the `cpu.cfs_quota_us` and `cpu.cfs_period_us` parameters) to limit the maximum CPU time slice a process can occupy within a unit time period. For example, setting the quota to 50,000 microseconds and the period to 100,000 microseconds means that the running process can only use a maximum of 50% of the single-core CPU computing power, or by setting multi-core affinity to restrict it to running on a specific CPU core. The memory usage limit can be set by configuring the memory subsystem (the `memory.limit_in_bytes` parameter) to set the maximum number of physical memory bytes that a process can allocate. For example, the limit can be set to 536,870,912 bytes, or 512 megabytes. Once a process attempts to request more memory than this value, the kernel's memory management module will trigger a memory reclamation mechanism (such as directly killing the process or triggering the OOM Killer) to forcibly terminate the process to protect system stability. By setting limits on CPU usage and memory usage, resource fairness and overall system robustness are ensured in a multi-tenant environment.

[0081] By reusing runtime processes from a pre-defined process pool, combined with view isolation implemented through namespaces and hard resource constraints implemented through control group mechanisms, the method provided in this application constructs an execution environment that combines high-performance startup with strict resource isolation. This construction approach ensures that the plugin code of different tenants is logically completely independent and is strictly controlled in terms of physical resource consumption, thereby solving the problem of secure isolation and performance balance in code execution in a multi-tenant environment without the need to introduce heavy virtualization technology.

[0082] Example 4:

[0083] In another embodiment, the system call filter in the plug-in code execution method in a multi-tenant environment provided in this application is further configured with conditional restriction rules for sensitive system calls. These conditional restriction rules include: restricting the operation path of open-type system calls to a preset temporary directory, and / or restricting the connection target of network connection-type system calls to a preset address whitelist.

[0084] Specifically, the aforementioned conditional restrictions are fine-grained supplementary constraints to the system call whitelist, aiming to address the potential security bypass risks that may arise from filtering solely based on system call numbers. While a pre-defined system call whitelist can intercept the vast majority of dangerous operations, attackers may still gain unauthorized access by passing malicious parameters in some permitted system calls. Therefore, inspecting the parameter content of system calls at the kernel level can further tighten the security boundary.

[0085] For open-type system calls, path checking logic is implemented in the filter. When a process attempts to execute open-type system calls such as `open` or `openat`, in addition to verifying that the call type is on the whitelist, the passed file path parameter is also validated. This logic forcibly restricts the operation path to a preset temporary directory, such as ` / tmp` or a specific sandbox directory inside the container. Any system call request attempting to open a file outside this preset temporary directory, even if its call number is valid, will be rejected by the kernel. This restriction prevents plugin code from attempting to read, modify, or write sensitive files on the host machine or other tenants.

[0086] For network connection system calls, strict connection target restrictions are implemented. When plugin code attempts to establish a network connection (such as via the `connect` system call), the target address parameter is parsed and compared with a preset address whitelist. The connection request is only allowed if the target IP address or port number exists in the preset address whitelist. This preset address whitelist can be configured to specific internal network addresses for platform services or external third-party API addresses required by business logic.

[0087] By imposing parameter-level constraints on open and network connection system calls, a more robust defense-in-depth system is constructed. Even if attackers bypass static code analysis or exploit language-level sandbox vulnerabilities, they still cannot carry out data theft, lateral movement, or denial-of-service attacks through restricted system calls, thus effectively ensuring data isolation and system security in a multi-tenant environment.

[0088] Example 5:

[0089] In another embodiment, a method for determining the scheduling priority of execution tasks in a scene queue before determining the execution task based on the execution request through rate limiting is provided in a plug-in code execution method in a multi-tenant environment according to an embodiment of this application.

[0090] Before determining the execution task based on the execution request that has passed rate limiting, the method may further include: dividing the execution task corresponding to the execution request that has passed rate limiting into the corresponding scenario queue based on the scenario identifier of the execution request that has passed rate limiting, and determining the scheduling priority of the execution task in the scenario queue based on the waiting time of the execution task in the scenario queue.

[0091] Specifically, a traffic isolation mechanism based on business scenarios is introduced at the task scheduling level. Scenario identifiers, as key metadata representing the business type or urgency of the current execution request, are transmitted by the caller when initiating the execution request and are obtained after the aforementioned rate limiting process. Given the significant differences in system resource requirements and response latency requirements among different business scenarios in a multi-tenant SaaS platform—for example, real-time form calculations prioritize extremely low response latency, while large-scale data export tasks focus more on throughput—different types of tasks need to be processed separately. The obtained scenario identifiers are parsed, and the execution requests, after tenant-level rate limiting, are routed to specific scenario queues. Each scenario queue corresponds to an independent buffer for temporarily storing execution tasks with the same scenario identifier. This partitioning method allows the scheduling system to implement differentiated resource allocation strategies for different scenario characteristics, effectively preventing high-density offline tasks from crowding out the computing resources of real-time tasks. The mapping relationship between scenario identifiers and scenario queues can adopt a pre-configured key-value pair structure to support dynamic expansion.

[0092] This system dynamically adjusts task scheduling weights through a time-based feedback mechanism to address task starvation issues that can arise from traditional fixed-priority scheduling. Waiting time refers to the duration from when a task enters the queue until the current moment, periodically calculated by the scheduling system in the background. The scheduling priority of a task in the current queue is calculated based on this waiting time; the core logic is that the task's scheduling priority increases with the waiting time. This dynamic priority adjustment mechanism ensures that even under high system load and continuous high-priority task generation, low-priority tasks that remain in the queue for extended periods can gradually improve their scheduling order due to accumulated waiting time, eventually gaining an execution opportunity. Specifically, the waiting time can be substituted into a preset priority calculation function, configured as a monotonically increasing function of the waiting time. When the waiting time exceeds a preset starvation threshold, the task's priority is automatically raised to the highest or near-highest level in the current queue, thus ensuring system fairness.

[0093] Furthermore, this application provides a method for determining the execution task based on the execution request that has been rate-limited in a plug-in code execution method in a multi-tenant environment.

[0094] Based on the scheduling priority of the tasks in the scene queue, the target task is determined from the tasks in the scene queue using a task-level scheduling strategy, which includes the shortest job first strategy or the priority queue strategy.

[0095] Specifically, within a defined scenario queue, the most urgent task to be executed at any given time is selected based on a task-level scheduling strategy. The task-level scheduling strategy, as the core set of algorithms for determining the execution order of tasks in the scheduling system, works in conjunction with a priority mechanism based on waiting time. The Shortest Job First (SJF) strategy prioritizes tasks with the shortest estimated execution time, aiming to reduce average waiting time and response latency by minimizing the blocking time of long tasks on short tasks, thereby improving system throughput. The priority queue strategy strictly follows the determined scheduling priorities, always prioritizing the highest priority tasks. In actual operation, one strategy or a combination of strategies can be flexibly selected based on the current system load and performance indicators. For example, the Shortest Job First strategy can be used to maximize processing efficiency when the system is idle, while the priority queue strategy can be switched to ensure timely response to high-priority tasks when the system is busy. The target tasks selected by the above strategies will be assigned to isolated processes and enter the subsequent plugin code execution phase.

[0096] The process described above—dividing queues based on scenario identifiers, dynamically adjusting priorities based on waiting time, and selecting tasks using task-level scheduling strategies—constitutes the core of the multi-dimensional hybrid scheduling algorithm. By introducing the scenario dimension, logical isolation and differentiated management of traffic from different business types are achieved; the priority-boosting mechanism based on waiting time effectively prevents indefinite blocking of specific tasks under high system load; and the flexible task-level scheduling strategy ensures both response speed and overall system throughput efficiency. The synergistic effect of these technical features enables this application to maintain fairness and efficiency in task scheduling within a multi-tenant, high-concurrency environment, avoiding task backlog and tenant starvation.

[0097] Example 6:

[0098] In another embodiment, a method for executing plugin security code in an isolated process to obtain plugin code execution results is provided in a plugin code execution method in a multi-tenant environment according to an embodiment of this application.

[0099] Set an execution timeout for the isolation process. When the execution time of the plugin security code does not exceed the timeout, it interacts with the business platform corresponding to the multi-tenant environment via a secure application programming interface to obtain the plugin code execution result. When the execution time of the plugin security code exceeds the timeout, the isolation process is terminated.

[0100] Specifically, the execution timeout, a key parameter for ensuring system stability, is set based on statistical analysis and security policy assessment of plugin execution times across various business scenarios in a multi-tenant environment. This process aims to impose hard constraints on plugin behavior from a time perspective, preventing prolonged resource occupation due to code logic errors (such as infinite loops or deadlocks) or malicious attacks. The execution timeout can be determined, for example, by collecting historical plugin execution samples during the system configuration phase, calculating the average execution time and standard deviation required for normal completion, and combining this with the Service Level Agreement (SLA) requirements for response time to set a threshold that covers most normal execution scenarios while providing a safety margin. For example, for real-time interactive scenarios, this time could be set to 3 to 5 seconds; for offline batch processing scenarios, it could be set to 30 to 60 seconds. This parameter is configured in the task scheduler or runtime monitoring module, and the timer starts when a task is assigned to an isolated process.

[0101] The secure Application Programming Interface (API) is the sole controlled channel for communication between the plugin logic and the main platform of the multi-tenant environment. Its design adheres to the principle of least privilege and type-safety verification mechanisms. This secure API is not a native operating system interface, but rather a set of encapsulated middleware interfaces provided in this application, shielding sensitive operations and direct data access at the underlying level. At the dynamic execution level, when plugin code needs to read tenant data, call platform services, or write business state, it must initiate a request through this secure API. Upon receiving the request, the API executes a series of verification logic: for example, verifying whether the request context matches the current tenant's identity, checking whether the parameter types conform to the preset serialization format, and confirming whether the target resource is within the allowed access range. Only requests that pass verification are forwarded to the business platform for processing, thus ensuring the security of the data interaction process. The plugin code execution results typically include the processing results of business data, status codes, and necessary metadata. These results, returned through the secure API, are uniformly encapsulated by the runtime environment and fed back to the caller. In this way, even within the isolated process, the plugin code cannot bypass the security barrier to directly access system resources, achieving dual protection for code execution and data security.

[0102] Terminating isolated processes is the last line of defense in the system's resource reclamation mechanism, designed to forcibly interrupt abnormal or malicious computation processes and prevent cascading failures. Execution duration monitoring is typically handled by a separate timer or monitoring thread. This monitoring component runs asynchronously with the execution logic of the isolated process, ensuring that even if the isolated process itself gets stuck in an infinite loop and cannot respond proactively, it can be forcibly terminated by external control measures. When the monitoring component detects that the current runtime has reached or exceeded the preset execution timeout, it immediately triggers a termination signal. In a Linux operating system environment, this could be, for example, sending a SIGKILL signal to the isolated process. This signal is directly handled by the kernel, forcibly terminating the process and all its child threads; it cannot be ignored or caught. The termination process not only includes the destruction of the process itself but also involves resource reclamation at the operating system kernel level: releasing the CPU time slice occupied by the process, reclaiming memory pages, closing open file descriptors, and cleaning up network sockets, etc. Furthermore, if the terminated process was allocated from the preheating pool, after termination, the system will decide whether to directly destroy the process or clean it up, reinitialize it, and rejoin it in the pool, depending on the degree of process contamination. This forced termination mechanism can control the negative impact of abnormal plugins within a single isolated process, preventing them from exhausting system resources and causing overall service unavailability, thereby maintaining the high availability and fairness of the multi-tenant platform.

[0103] The above steps, by setting time thresholds and a forced termination mechanism, strictly limit the execution behavior of the plugin code to a controllable time window; simultaneously, combined with the controlled interaction mode of the secure application programming interface, they ensure the security of data flow under normal execution paths. This strategy, combining timeout control and secure interaction, effectively solves the service blocking problem that may be caused by abnormal code, and ensures the fairness of resource allocation and the overall robustness of the system in a multi-tenant environment.

[0104] Example 7:

[0105] In another embodiment, a method for returning the released isolated process to a preset process pool after obtaining the plugin code execution result is provided in a plugin code execution method in a multi-tenant environment according to an embodiment of this application.

[0106] After assigning the task to an isolated process, executing the plugin security code within the isolated process, and obtaining the plugin code execution result, the method may further include: clearing global variables in the isolated process, closing network connections in the isolated process, and releasing the memory occupied by the isolated process. The released isolated process is then returned to the preset process pool.

[0107] Specifically, after obtaining the execution results of the plugin code, a state cleanup operation is performed on the isolated process to eliminate potential interference from preceding tasks to subsequent tasks, maintaining data isolation and system stability in the multi-tenant environment. First, the global object namespace in the isolated process's runtime environment is traversed and reset, removing custom attributes, function references, and cached data defined by preceding tasks, restoring the runtime environment to its initial clean state. This process can be achieved by retaining an initial global object snapshot and using this snapshot to overwrite the current global object after each task; alternatively, it can be performed by explicitly deleting non-retained fields.

[0108] For network connection resources, all socket connections established by preceding tasks are proactively terminated, including Hypertext Transfer Protocol (HTTP) connections, database connections, or other long-lived connections, to prevent file descriptor exhaustion due to connection leaks. Simultaneously, the language runtime's garbage collection mechanism or system-level memory management interface is invoked to reclaim heap memory space occupied by unused objects, arrays, and other data structures, ensuring that memory usage falls back to within a preset safe baseline. Through this combined cleanup action, execution traces of preceding tasks are thoroughly erased, preventing data residue or state pollution between different tenants and creating a clean, isolated execution environment for the next task allocation.

[0109] After the state cleanup is complete, the isolated processes in an idle state will be re-injected into the resource management system. Specifically, the handles or identifiers of the isolated processes that have been cleaned up and are in a standby state will be returned to the available resource list of the preset process pool. The preset process pool is a container that is pre-maintained during the system initialization phase to store and manage a certain number of idle isolated process instances.

[0110] When a new execution request arrives and is scheduled for process execution, an isolated process that has already been initialized and reset is directly obtained from the preset process pool, thus eliminating time-consuming operations such as process creation, runtime loading, and environment initialization. This process reuse mechanism significantly shortens cold start time, controls task execution latency to the millisecond level, and improves the system's concurrent processing capabilities and response speed. Simultaneously, this mechanism allows the system to dynamically adjust the process pool size based on actual load, effectively controlling overall resource consumption while ensuring high performance, and avoiding the context switching overhead and system pressure caused by frequent process creation and destruction.

[0111] The resource recycling and reuse mechanism described above ensures thorough environment cleanup and efficient resource turnover after each plugin code execution. This mechanism not only eliminates the risk of state interference that may exist in a multi-tenant environment and ensures the security and independence of task execution for different tenants, but also significantly reduces the average latency of task scheduling through preheating pool technology, achieving dual optimization of system resource utilization and service response performance.

[0112] This application also provides an electronic device in its embodiments. (See reference...) Figure 2 The diagram illustrates a structural schematic suitable for implementing the electronic device in the embodiments of this application. The electronic device in the embodiments of this application may include, but is not limited to, fixed terminals such as mobile phones, laptops, PDAs (personal digital assistants), PADs (tablet computers), desktop computers, etc. Figure 2 The electronic device shown is merely an example and should not impose any limitation on the functionality and scope of use of the embodiments of this application.

[0113] like Figure 2 As shown, the electronic device may include a processing unit (e.g., a central processing unit, a graphics processing unit, etc.) 201, which can perform various appropriate actions and processes according to a program stored in a read-only memory (ROM) 202 or a program loaded from a storage device 208 into a random access memory (RAM) 203. When the electronic device is powered on, the RAM 203 also stores various programs and data required for the operation of the electronic device. The processing unit 201, ROM 202, and RAM 203 are interconnected via a bus 204. An input / output (I / O) interface 205 is also connected to the bus 204.

[0114] Typically, the following devices can be connected to I / O interface 205: input devices 206 including, for example, touchscreens, touchpads, keyboards, mice, cameras, microphones, accelerometers, gyroscopes, etc.; output devices 207 including, for example, liquid crystal displays (LCDs), speakers, vibrators, etc.; storage devices 208 including, for example, memory cards, hard drives, etc.; and communication devices 209. Communication device 209 allows electronic devices to communicate wirelessly or wiredly with other devices to exchange data. Although Figure 2 Electronic devices with various devices are shown, but it should be understood that it is not required to implement or have all of the devices shown. More or fewer devices may be implemented or have alternatively.

[0115] This application also provides a computer program product including computer-readable instructions, which, when executed on an electronic device, cause the electronic device to implement any of the plug-in code execution methods provided in this application's embodiments under a multi-tenant environment.

[0116] This application also provides a computer-readable storage medium that carries one or more computer programs. When the one or more computer programs are executed by an electronic device, the electronic device can implement any of the plug-in code execution methods provided in the multi-tenant environment of this application.

[0117] It should also be noted that the device embodiments described above are merely illustrative. The units described as separate components may or may not be physically separate, and the components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the modules can be selected to achieve the purpose of this embodiment according to actual needs. In addition, in the device embodiment drawings provided in this application, the connection relationship between modules indicates that they have a communication connection, which can be implemented as one or more communication buses or signal lines.

[0118] Through the above description of the embodiments, those skilled in the art can clearly understand that this application can be implemented by means of software plus necessary general-purpose hardware, or it can be implemented by special-purpose hardware including application-specific integrated circuits, special-purpose CPUs, special-purpose memory, special-purpose components, etc. Generally, any function performed by a computer program can be easily implemented by corresponding hardware, and the specific hardware structure used to implement the same function can also be diverse, such as analog circuits, digital circuits, or special-purpose circuits. However, for this application, software program implementation is more often the preferred implementation method. Based on this understanding, the technical solution of this application, in essence, or the part that contributes to the prior art, can be embodied in the form of a software product. This computer software product is stored in a readable storage medium, such as a computer floppy disk, USB flash drive, mobile hard disk, ROM, RAM, magnetic disk, or optical disk, etc., and includes several instructions to cause a computer device (which may be a personal computer, training equipment, or network device, etc.) to execute the methods described in the various embodiments of this application.

[0119] In the above embodiments, the implementation can be achieved, in whole or in part, through software, hardware, firmware, or any combination thereof. When implemented in software, it can be implemented, in whole or in part, in the form of a computer program product.

[0120] The computer program product includes one or more computer instructions. When the computer program instructions are loaded and executed on a computer, all or part of the processes or functions described in the embodiments of this application are generated. The computer may be a general-purpose computer, a special-purpose computer, a computer network, or other programmable device. The computer instructions may be stored in a computer-readable storage medium or transmitted from one computer-readable storage medium to another. For example, the computer instructions may be transmitted from one website, computer, training device, or data center to another website, computer, training device, or data center via wired (e.g., coaxial cable, fiber optic, digital subscriber line (DSL)) or wireless (e.g., infrared, wireless, microwave, etc.) means. The computer-readable storage medium may be any available medium that a computer can store or a data storage device such as a training device or data center that integrates one or more available media. The available media may be magnetic media (e.g., floppy disks, hard disks, magnetic tapes), optical media (e.g., DVDs), or semiconductor media (e.g., solid-state drives (SSDs)).

Claims

1. A method for executing plugin code in a multi-tenant environment, characterized in that, include: Obtain the plugin source code submitted by the target tenant in a multi-tenant environment, and perform structural analysis on the plugin source code to obtain the plugin security code; An isolation process is constructed, and a system call filter configured with a preset system call whitelist is loaded into the isolation process. The amount of resources that the isolation process can use is limited by a preset quota. In response to an execution request for the security code of the plugin, the execution request is rate-limited based on the resource quota of the target tenant, and the execution task is determined based on the execution request that passes the rate limit; The execution task is assigned to the isolated process, and the plugin security code is executed in the isolated process to obtain the plugin code execution result.

2. The plug-in code execution method in a multi-tenant environment according to claim 1, characterized in that, The structural analysis of the plugin source code to obtain the plugin security code includes: The abstract syntax tree engine is invoked to perform structural parsing on the plugin source code, thereby obtaining the abstract syntax tree of the plugin source code; Based on preset security rules, multiple nodes of the abstract syntax tree are traversed, and the code fragments corresponding to the nodes that do not match the preset security rules are identified as risky code fragments in the plugin source code. The risky code snippets in the plugin's source code are rewritten to obtain the safe code for the plugin.

3. The plug-in code execution method in a multi-tenant environment according to claim 1, characterized in that, The process of constructing the isolation process includes: Obtain pre-started runtime processes from the preset process pool; An independent resource view is created for the runtime process by invoking the namespace mechanism of the operating system kernel; The operating system kernel's control group mechanism is invoked to set the preset quotas for the runtime process. The preset quotas include the upper limit of CPU usage and the upper limit of memory usage.

4. The plug-in code execution method in a multi-tenant environment according to claim 1, characterized in that, The system call filter is also configured with conditional restriction rules for sensitive system calls; The condition restriction rules include: restricting the operation path of open system calls to a preset temporary directory, and / or restricting the connection target of network connection system calls to a preset address whitelist.

5. The plug-in code execution method in a multi-tenant environment according to claim 1, characterized in that, Before determining the execution task based on the execution request via rate limiting, the method further includes: Based on the scenario identifier of the execution request that passed the rate limiting, the execution task corresponding to the execution request that passed the rate limiting is divided into the corresponding scenario queue, and the scheduling priority of the execution task in the scenario queue is determined based on the waiting time of the execution task in the scenario queue. The step of determining the execution task based on the execution request through rate limiting includes: Based on the scheduling priority of the tasks to be executed in the scenario queue, a target task to be executed is determined from the tasks to be executed in the scenario queue using a task-level scheduling strategy, which includes a shortest job priority strategy or a priority queue strategy.

6. The plug-in code execution method in a multi-tenant environment according to claim 1, characterized in that, The execution of the plugin security code in the isolation process, and the resulting plugin code execution, includes: Set an execution timeout for the isolation process; When the execution time of the plugin security code does not exceed the execution timeout, data interaction is performed with the business platform corresponding to the multi-tenant environment through the security application programming interface to obtain the execution result of the plugin code; The isolation process is terminated when the execution time of the plugin security code exceeds the execution timeout period.

7. The plug-in code execution method in a multi-tenant environment according to claim 1, characterized in that, After assigning the execution task to the isolated process, executing the plugin security code in the isolated process, and obtaining the plugin code execution result, the method further includes: Clear global variables in the isolation process, close network connections in the isolation process, and release memory occupied by the isolation process; The isolated process is then returned to the preset process pool after being released.

8. A computer program product, characterized in that, It includes computer-readable instructions that, when executed on an electronic device, cause the electronic device to implement the plug-in code execution method in a multi-tenant environment as described in any one of claims 1 to 7.

9. An electronic device, characterized in that, It includes at least one processor and a memory connected to the processor, wherein: The memory is used to store computer programs; The processor is used to execute the computer program to enable the electronic device to implement the plug-in code execution method in a multi-tenant environment as described in any one of claims 1 to 7.

10. A computer storage medium, characterized in that, The storage medium carries one or more computer programs, which, when executed by an electronic device, enable the electronic device to implement the plug-in code execution method in a multi-tenant environment as described in any one of claims 1 to 7.