目录

Memory Optimization Practices: Remote Build

Overview

Remote build is a development optimization solution that migrates build tasks from local devices to remote servers. It applies to large-scale projects where local memory is insufficient to support full builds. Remote build offloads memory-intensive tasks to more powerful servers, keeping local development responsive.

Workflow

On the local side, synchronize code and build information to the remote server via the rsync service. After the server completes the build, it synchronizes build products back to the local side. The client polls to monitor build status and waits for the build to finish.

Throughout this process, actual build work is undertaken by the remote server. The local side only triggers the build and receives results, and does not need to retain complete intermediate build products. This effectively frees up local memory resources.

Example

This example implements remote build using rsync, the Hvigor plugin, and Python scripts, which is for reference only. You may implement remote build through other approaches.

Before using the capabilities described in this topic, you need basic knowledge of rsync and Python development.

[h2]Client-side Configuration

The client runs on your development device and is responsible for synchronizing code and build information to the remote server. Create the following files manually and place them in any directory according to your actual environment.

  1. Create the config.json file to specify parameters such as the rsync command and the path to the monitored file. The following is an example. You can change parameter names or add parameters as required.
    // Only key fields are described in this example. For other fields, see the sample code. Replace paths, IP addresses, and other content with actual values.
    {
      "rsyncType": "client",   // This indicates that the current configuration is for the client side.
      "monitor": {
        "trigger_file": "/path/to/client/trigger.json"  // Path to the build information file. The client monitors this file for changes in build status. trigger.json is used as an example.
      },
      "rsyncCommand": "rsync -rltvz --no-o --no-g --timeout=90000 --exclude-from=/path/to/client/exclude.txt /path/to/project rsync://user@server_ip:873/basetest",  // rsync command for synchronizing local source code to a remote server.
      "origin": {
        "base_dir": "/path/to/project" // Project path.
      },
      "output": {
        "host": "server_ip" // IP address of the server.
      }
    }
  2. If certain files or directories should not be synchronized to the remote server, append the --exclude-from parameter to the rsync command to skip them. For example, specify files or directories to exclude in exclude.txt:
    // Set fields as required.
    .git/
    .idea/
    node_modules/
    oh_modules/
    **/build
    **/build/**
    **/.hvigor/**
    .appanalyzer
  3. Create the rsyncd.conf file to start the local rsync service. The following is an example:
    // The rsyncd.conf configuration is not fixed. This example is for reference only for remote build scenarios. Modify parameter values based on your actual environment.
    use chroot = false
    strict modes = false
    hosts allow = *
    log file = rsyncd.log
    pid file = rsyncd.pid
    port = 873
    uid = your_user
    gid = your_group
    [basetest]
    path = /path/to/project/parent
    read only = false
    [client]
    path = /path/to/client/config
    read only = no
  4. Download remote-plugin.ts from the sample code and replace configPath, filePath, and oldFilePath in the code with actual paths.
    The remote-plugin.ts file creates, reads, and writes the build information file (the file specified by trigger_file in the config.json file, which is trigger.json in this example), and polls to monitor the build status. The build information file records information such as build commands and build status. You can also use it to record other information as needed.

    In this example, process.argv is used to parse build arguments to generate the build command. Before this can work, the local daemon process must be stopped so that the arguments can be read correctly. Alternatively, you can directly write the build command in the plugin for invocation. There is no restriction on how you obtain the build command; choose the approach that best fits your scenario.

    Import remote-plugin.ts in the project-level hvigorfile.ts file.

    import { appTasks } from '@ohos/hvigor-ohos-plugin';
    import { remoteBuildPlugin } from '/path/to/remote-plugin';  // Replace it with your actual path.
    
    export default {
      system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
      plugins: [
        remoteBuildPlugin()
      ]       /* Custom plugin to extend the functionality of Hvigor. */
    }
  5. Create a Python script for the client. For details, see client/rsync_client.py in the sample code. The script reads and writes the build information file, polls to monitor the build status, and synchronizes code and build information to the remote server. The main functions are described as follows:
    # Configuration loading
    load_client2_config()        # Parse the config.json file and extract configurations.
    build_remote_spec()          # Construct the destination address for rsync.
    
    # JSON file operations
    read_json() / write_json()   # Read or write JSON files.
    update_trigger_status()      # Updates the build status in trigger.json.
    
    # Lock management
    acquire_lock() / release_lock()  # Acquire or release a mutex lock based on the .lock file to prevent concurrent builds.
    
    # Code synchronization
    sync_to_remote()             # Synchronize code to the server via rsync.
    
    # File monitoring
    monitor_trigger_file()       # Monitor changes to trigger.json (using watchdog or polling fallback).
    to_cygdrive_path()           # Convert a Windows path to the cygdrive format.
    
    # Error handling
    write_console_file()         # Write error logs to console.file.
    
    # Program entry
    main()                       # Program entry, starting the monitoring loop.
  6. Start the rsync service and run the Python script on the client.

[h2]Server-side Configuration

  1. Create the config.json file to specify parameters such as the rsync command and the path to the monitored file. The following is an example. You can change parameter names or add parameters as required.
    // Only key fields are described in this example. For other fields, see the sample code. Replace paths, IP addresses, and other content with actual values.
    {
      "rsyncType": "server",   // This indicates that the current configuration is for the server side.
      "monitor": {
        "trigger_file": "/path/to/server/trigger.json"  // Path to the build information file. The server monitors this file for changes in build status. trigger.json is used as an example.
      },
      "rsyncCommand": "rsync -rltvz --no-o --no-g --timeout=9000 --exclude-from=/path/to/server/exclude.txt /path/to/project rsync://user@client_ip:873/basetest",  // rsync command for synchronizing build products and logs from the server to the client.
      "build": {
        "base_path": "/path/to/project"  // Project path.
      },
      "output": {
        "host": "client_ip",  // IP address of the client.
      }
    }
  2. If certain files or directories should not be synchronized to the client, append the --exclude-from parameter to the rsync command to skip them. For example, specify files or directories to exclude in exclude.txt:
    // Set fields as required.
    .git/
    .idea/
    *.iml
    node_modules/
    oh_modules/
    *.log
  3. Create the rsyncd.conf file to start the rsync service on the server. The following is an example:
    // The rsyncd.conf configuration is not fixed. This example is for reference only for remote build scenarios. Modify parameter values based on your actual environment.
    syslog facility = 0
    log file = /path/to/server/log/rsyncd.log
    uid = your_user
    gid = your_group
    use chroot = no
    port = 873
    strict modes = false
    timeout = 60000
    # Module configuration
    [basetest]
    path = /path/to/project/parent
    read only = no
    [server]
    path = /path/to/server/config
    read only = no
  4. Create a Python script on the server. For details, see server/rsync_server.py in the sample code. The script reads and writes the build information file, polls to monitor the build status, executes build tasks, and synchronizes build products and information to the client. The main functions are described as follows:
    # Configuration loading
    load_server2_config()        # Parse the config.json file and extract configurations.
    build_remote_spec()          # Construct the destination address for rsync.
    
    # JSON file operations
    read_json() / write_json()   # Read or write JSON files.
    update_trigger_status()      # Updates the build status in trigger.json.
    
    # Lock management
    acquire_lock() / release_lock()  # Acquire or release a mutex lock based on the .lock file to prevent concurrent builds.
    
    # Build command execution
    execute_node_build()         # Execute the build command, with timeout control supported.
    terminate_process_tree()     # Terminate the build process tree.
    
    # Product synchronization
    sync_to_remote()             # Synchronize products to the client via rsync.
    
    # File monitoring
    monitor_trigger_file()       # Monitor changes to trigger.json (using watchdog or polling fallback).
    to_cygdrive_path()           # Convert a Windows path to the cygdrive format.
    
    # Error handling
    write_console_file()         # Write error logs to console.file.
    
    # Program entry
    main()                       # Program entry, starting the monitoring loop.
  5. Start the rsync service and run the Python script on the server.

[h2]Starting the Build

After starting the rsync service and running the Python script, triggering a build locally will automatically migrate the build task to the remote server.

[h2]Sample Code