Shannon-Data / ShannonBase

A MySQL HTAP Database, Open Source version of MySQL Heatwave, Powered by AI.
https://www.shannonbase.org
Other
13 stars 6 forks source link

feat(shannon): Resource management #34

Open RingsC opened 7 months ago

RingsC commented 7 months ago

It's a key module to HTAP. TP workloads and AP workloads dont interfere with each other. AKA resource isolation.

ShannonBase commented 1 month ago

A demo to show how to use cgroup to manage the compute resource.

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define CGROUP_FOLDER "/sys/fs/cgroup/cpu/demo_cgroup"
#define CPU_QUOTA_FILE "/sys/fs/cgroup/cpu/demo_cgroup/cpu.cfs_quota_us"
#define CPU_PERIOD_FILE "/sys/fs/cgroup/cpu/demo_cgroup/cpu.cfs_period_us"
#define TASKS_FILE "/sys/fs/cgroup/cpu/demo_cgroup/tasks"

void write_to_file(const std::string &file_path, const std::string &content) {
    std::ofstream file(file_path);
    if (file.is_open()) {
        file << content;
        file.close();
    } else {
        std::cerr << "Failed to open " << file_path << std::endl;
        exit(EXIT_FAILURE);
    }
}

void setup_cgroup() {
    // Create cgroup directory
    if (system(("mkdir -p " + std::string(CGROUP_FOLDER)).c_str()) != 0) {
        std::cerr << "Failed to create cgroup folder." << std::endl;
        exit(EXIT_FAILURE);
    }

    // Set CPU quota and period
    write_to_file(CPU_QUOTA_FILE, "50000"); // 50ms quota
    write_to_file(CPU_PERIOD_FILE, "100000"); // 100ms period
}

void add_self_to_cgroup() {
    // Get current process ID
    pid_t pid = getpid();

    // Add this process to the cgroup
    write_to_file(TASKS_FILE, std::to_string(pid));
}

int main() {
    setup_cgroup();
    add_self_to_cgroup();

    // Simulate some CPU intensive work
    std::cout << "Starting CPU intensive task..." << std::endl;
    for (int i = 0; i < 1000000000; ++i) {
        // Busy work
        if (i % 100000000 == 0) {
            std::cout << "Working... " << i << std::endl;
        }
    }

    std::cout << "Task completed." << std::endl;
    return 0;
}