DEV Community

SameX
SameX

Posted on

Service Status Monitoring System in HarmonyOS High - Concurrency Environment

This article deeply explores the inter - process communication and service monitoring technologies of the HarmonyOS IPC Kit, and demonstrates how to build a high - concurrency service status monitoring system to manage the running status of multiple service processes in real time and ensure that the recovery operation and resource recovery mechanism are triggered when the process terminates unexpectedly. This article aims to help developers master the core functions of the IPC Kit such as asynchronous communication and termination notification subscription, and provide practical guidance for the development of high - concurrency monitoring systems.

1. Case Background and Requirement Analysis

In a complex system environment, multiple service processes run in parallel and complete different tasks. With the increase in the number of services and system load, the stability of service processes becomes crucial. If a certain process terminates unexpectedly, the system needs to detect the abnormal status in time and take corresponding measures. An efficient service status monitoring system can monitor the running status of multiple processes in real time, and automatically execute recovery and alarm operations when a process fails, thereby improving the reliability of the system.
Target Requirements:

  • Real - Time Monitoring of Service Processes: Monitor the running status of multiple processes and obtain the status changes of service processes in time.
  • Asynchronous Invocation and High - Concurrency Processing: Support service status monitoring in a high - concurrency environment and ensure rapid system response.
  • Resource Recovery and Termination Notification: Clean up resources when a process terminates unexpectedly and trigger automatic recovery or alarm. Involved Technologies:
  • IPC Kit Client - Server Model: Realize the sharing of service status between processes through Client - Server communication.
  • Asynchronous Invocation and Multithreading Management: Realize efficient monitoring through multithreading and asynchronous invocation mechanisms.

- Process Termination Notification and Resource Management: Use DeathRecipient to monitor process status changes and ensure resource recovery and error handling.

2. System Architecture Design

This service status monitoring system is divided into a monitoring process and monitored processes. The monitoring process acts as the server and receives the status information of the monitored processes. Through IPC communication and asynchronous invocation, the monitoring process can manage the service status in real time and ensure stability in a high - concurrency situation.

Architecture Modules

  1. Monitored Process Module: Each service process (such as service process A, service process B, etc.) periodically sends the running status to the monitoring process.
  2. Monitoring Process Module: The server process asynchronously receives the status information of each monitored process and manages the process status changes through the termination notification mechanism.

3. Resource Recovery and Restoration Module: After detecting that a certain service process terminates abnormally, automatically clean up the occupied resources and attempt to restart the service.

3. Multithreaded Task Management and Asynchronous Processing

To ensure that the monitoring process can efficiently handle service status update requests in a high - concurrency environment, a multithreading and asynchronous communication mechanism is adopted. The monitored process sends status messages through the SendRequest method, and the monitoring process asynchronously receives and processes these messages in a multithreading environment.

  1. Monitored Process Configures IPC Client Interface: Send the service status information to the monitoring process through the IPC Kit proxy.
  2. Implementation of Asynchronous Communication: The monitored process asynchronously calls SendRequest to realize the non - blocking sending of status messages.
  3. Shared Memory Transmission of Large Data: To avoid resource competition, use shared memory to transmit large data blocks. #### Sample Code The following code shows how the monitored process sends service status information asynchronously:
#include <IPCKit/ipc_kit.h>
#include <thread>
class ServiceProcess {
public:
    ServiceProcess(OHIPCRemoteProxy* proxy) : proxy_(proxy) {}
    // Simulate service status update
    void UpdateStatus(int status) {
        std::thread([this, status]() {
            OHIPCParcel *data = OH_IPCParcel_Create();
            if (data!= nullptr) {
                OH_IPCParcel_WriteInt32(data, status);  // Write status data
                SendStatusAsync(data);
                OH_IPCParcel_Destroy(data);
            }
        }).detach();
    }
private:
    void SendStatusAsync(OHIPCParcel* data) {
        OH_IPC_MessageOption option = { OH_IPC_REQUEST_MODE_ASYNC, 0 };
        OHIPCParcel *reply = OH_IPCParcel_Create();
        int result = OH_IPCRemoteProxy_SendRequest(proxy_, 1, data, reply, &option);
       
        if (result == OH_IPC_SUCCESS) {
            printf("Status updated successfully!\n");
        } else {
            printf("Failed to update status!\n");
        }
       
        OH_IPCParcel_Destroy(reply);
    }
    OHIPCRemoteProxy* proxy_;
};
Enter fullscreen mode Exit fullscreen mode

In the monitored process, the UpdateStatus function sends the service status asynchronously to ensure that other tasks are not blocked due to status updates.

4. Process Status Monitoring and Resource Recovery Mechanism

The monitoring process needs to configure the DeathRecipient termination notification interface to monitor the status of the monitored processes in real time. When the monitored process exits abnormally, the monitoring process receives the notification, triggers resource cleanup and attempts to restart the service.

Steps

  1. Register Termination Notification: The monitoring process registers the termination notification through registerDeathRecipient to detect the status of the monitored processes.
  2. Resource Recovery and Restoration Mechanism: When a certain service process terminates abnormally, the monitoring process triggers the resource recovery mechanism to ensure that resources are released and executes an alarm or automatic service restart. #### Code Example The following code shows how the monitoring process registers the termination notification and triggers the resource recovery operation when the monitored process terminates:
#include <IPCKit/ipc_kit.h>
#include <unordered_map>
#include <mutex>
class MonitorProcess {
public:
    MonitorProcess() {
        remoteStub_ = OH_IPCRemoteStub_Create("SERVICE_MONITOR", OnStatusReceived, nullptr, this);
        RegisterDeathRecipient();
    }
    static int OnStatusReceived(uint32_t code, const OHIPCParcel* data, OHIPCParcel* reply, void* userData) {
        int status = 0;
        if (OH_IPCParcel_ReadInt32(data, &status) == OH_IPC_SUCCESS) {
            auto* monitor = static_cast<MonitorProcess*>(userData);
            monitor->UpdateStatus(status);
        }
        return OH_IPC_SUCCESS;
    }
    void RegisterDeathRecipient() {
        deathRecipient_.onRemoteDied = [](void* userData) {
            auto* monitor = static_cast<MonitorProcess*>(userData);
            monitor->HandleProcessDeath();
        };
        OH_IPCRemoteStub_AddDeathRecipient(remoteStub_, &deathRecipient_);
    }
    void UpdateStatus(int status) {
        std::lock_guard<std::mutex> lock(statusMutex_);
        currentStatus_ = status;
        printf("服务状态已更新: %d\n", status);
    }
    void HandleProcessDeath() {
        printf("被监控进程消亡,开始资源清理并尝试重启服务...\n");
        // Implement the resource recovery logic, clean up the allocated resources, and attempt to restore the service
    }
private:
    OHIPCRemoteStub* remoteStub_;
    int currentStatus_;
    std::mutex statusMutex_;
    OHIPCDeathRecipient deathRecipient_;
};
Enter fullscreen mode Exit fullscreen mode

In the MonitorProcess class, the RegisterDeathRecipient function is used to set the termination notification, and when the monitored process terminates unexpectedly, it calls HandleProcessDeath to perform resource cleanup.

5. Code Example and Architecture Analysis

In a high - concurrency monitoring system, the status update of service processes and the resource recovery of the monitoring process need to cooperate efficiently. The monitored process is responsible for reporting the status in real time, and the monitoring process improves communication efficiency through asynchronous invocation and shared memory.

Code Example: Combination of Multithreading and Shared Memory

// Set up shared memory on the server side to receive multiple service statuses
void InitSharedMemory() {
    sharedMemory = OH_IPCParcel_CreateSharedMemory("ServiceStatusBuffer", BUFFER_SIZE);
}
//
 定期从共享内存读取服务状态并执行处理
void ReadSharedMemory() {
    while (true) {
        std::lock_guard<std::mutex> lock(memoryMutex);
        int serviceStatus = 0;
        memcpy(&serviceStatus, sharedMemory, sizeof(serviceStatus));
        printf("读取服务状态: %d\n", serviceStatus);
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}
Enter fullscreen mode Exit fullscreen mode

The use of shared memory avoids data copying and further improves the processing performance of the system in a high - concurrency environment.

6. Summary

Through the service status monitoring system case in this article, we have learned how to use the IPC Kit of HarmonyOS to realize the real - time status monitoring of high - concurrency service processes. The system improves the processing efficiency through asynchronous invocation and multithreading, and combines process termination notification to realize the resource recovery and automatic recovery mechanism. We can draw on this system structure to achieve efficient and stable service process management in actual projects.
This architecture design and function implementation idea are not only applicable to service status monitoring, but also can be extended to the status management scenarios of various high - concurrency systems, providing some reference examples for the development of inter - process communication systems.

Top comments (0)