byteayan commented on code in PR #3355:
URL: https://github.com/apache/hugegraph/pull/3355#discussion_r4334078216


##########
hugegraph-store/hg-store-core/src/main/java/org/apache/hugegraph/store/options/RocksdbMemoryBudget.java:
##########
@@ -0,0 +1,450 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hugegraph.store.options;
+
+import java.io.IOException;
+import java.lang.management.ManagementFactory;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.OperatingSystemMXBean;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Resolves rocksdb.total_memory_size, the budget RaftRocksdbOptions splits 
into the
+ * write buffer manager's cache and the block cache. Both caches are off-heap, 
so an
+ * unset or "0" budget is sized from the memory left after the heap, direct 
memory and
+ * the fixed raft log cache, instead of a fixed number that can exceed a 
container limit.
+ */
+@Slf4j
+public final class RocksdbMemoryBudget {
+
+    public static final String KEY = "total_memory_size";
+
+    static final long MIB = 1024L * 1024L;
+    // The 1 GiB raft log block cache (RaftRocksdbOptions) plus thread stacks, 
metaspace
+    // and other native allocations that sit outside the budget
+    static final long RESERVED = 1024 * MIB + 512 * MIB;
+    static final long MIN_AUTO = 256 * MIB;
+    // RaftRocksdbOptions gives the write buffer manager 2/3 of the budget, 
and a 0-byte
+    // write buffer manager means no memtable limit at all
+    static final long MIN_EXPLICIT = MIB;
+    // The value shipped before auto-sizing; a large host never gets more than 
it had
+    static final long MAX_AUTO = 32_000_000_000L;
+
+    private RocksdbMemoryBudget() {
+    }
+
+    /**
+     * Returns the configured budget in bytes, or an automatic one when the 
value is
+     * missing, blank or 0.
+     */
+    public static long resolve(String configured) {
+        long value = isAuto(configured) ? 0L : parse(configured);
+        long heap = Runtime.getRuntime().maxMemory();
+        CgroupLimit cgroup = cgroupLimit(Paths.get("/proc/self/cgroup"),
+                                         Paths.get("/proc/self/mountinfo"),
+                                         Paths.get("/sys/fs/cgroup"));
+        long physical = effectivePhysical(jvmMemory(), cgroup.bytes);
+        if (value > 0) {
+            if (value < MIN_EXPLICIT) {
+                throw new IllegalArgumentException(String.format(
+                        "rocksdb.total_memory_size must be 0 (auto) or at 
least %s bytes, " +
+                        "got %s", MIN_EXPLICIT, value));
+            }
+            if (value < MIN_AUTO) {
+                log.warn("rocksdb.total_memory_size={} is below the {} bytes 
auto-sizing " +
+                         "never goes under", value, MIN_AUTO);
+            }
+            if (value == MAX_AUTO) {
+                // Most likely an application-pd.yml kept from before 
auto-sizing
+                log.warn("rocksdb.total_memory_size={} is the fixed value 
shipped before " +
+                         "auto-sizing; set it to 0 or remove it to size the 
budget from " +
+                         "the available memory", value);
+            }
+            long direct = maxDirectMemory(heap);
+            long left = physical - heap - direct - RESERVED;
+            if (physical > 0 && value > left) {
+                log.warn("rocksdb.total_memory_size={} exceeds the {} bytes 
left after the " +
+                         "heap, direct memory and the {} bytes reserve 
(physical={}, heap={}, " +
+                         "direct={}); the process may be OOM-killed",
+                         value, left, RESERVED, physical, heap, direct);
+            }
+            return value;
+        }
+        long direct = maxDirectMemory(heap);
+        long budget = auto(physical, heap, direct);
+        log.info("rocksdb.total_memory_size is unset or 0, auto-sizing to {} 
bytes " +
+                 "(physical={}, heap={}, direct={})", budget, physical, heap, 
direct);
+        if (cgroup.incomplete) {
+            log.warn("The cgroup mounts in /proc/self/mountinfo don't show 
this process's " +
+                     "whole cgroup hierarchy (an inherited mount in a cgroup 
namespace, or " +
+                     "only cgroup2 subtree mounts), so a tighter limit on the 
process's " +
+                     "cgroup or above the mounted subtree may be missed; set " 
+
+                     "rocksdb.total_memory_size or 
HG_STORE_ROCKSDB_TOTAL_MEMORY_SIZE " +
+                     "explicitly");
+        }
+        if (physical > 0 && physical - heap - direct - RESERVED < 2 * 
MIN_AUTO) {
+            log.warn("Heap, direct memory and the {} bytes reserve leave too 
little of the " +
+                     "{} bytes physical memory, rocksdb gets the {} bytes 
floor; lower -Xmx " +
+                     "or -XX:MaxDirectMemorySize", RESERVED, physical, 
MIN_AUTO);
+        }
+        return budget;
+    }
+
+    static boolean isAuto(String configured) {
+        return configured == null || configured.trim().isEmpty();
+    }
+
+    static long parse(String configured) {
+        try {
+            long value = Long.parseLong(configured.trim());
+            if (value < 0) {
+                throw new NumberFormatException("negative");
+            }
+            return value;
+        } catch (NumberFormatException e) {
+            throw new IllegalArgumentException(String.format(
+                    "rocksdb.total_memory_size must be a number of bytes, got 
'%s'",
+                    configured), e);
+        }
+    }
+
+    /**
+     * Half of what is left after the heap, direct memory and the reserve, 
clamped to
+     * [MIN_AUTO, MAX_AUTO]. Falls back to the heap size, the previous 
default, when
+     * physical memory is unknown.
+     */
+    static long auto(long physical, long heap, long direct) {
+        if (physical <= 0) {
+            return Math.min(Math.max(heap, MIN_AUTO), MAX_AUTO);
+        }
+        long available = physical - heap - direct - RESERVED;
+        return Math.min(Math.max(available / 2, MIN_AUTO), MAX_AUTO);
+    }
+
+    /**
+     * The raft disruptor buffer size AppConfig derives from the budget when
+     * raft.disruptorBufferSize is 0: the budget in GB, at least 1, rounded to 
a power
+     * of two, times 32.
+     */
+    public static int disruptorBufferSize(long totalMemory) {
+        // A budget under 1 GB would otherwise give log(0) and a zero-sized 
buffer
+        int size = (int) Math.max(1, totalMemory / 1000 / 1000 / 1000);
+        return (int) Math.pow(2, Math.round(Math.log(size) / Math.log(2))) * 
32;
+    }
+
+    /**
+     * The write_buffer_size AppConfig derives when the key is unset or 0: a 
thousandth
+     * of the budget, but never below the 1 MiB rocksdb.write_buffer_size 
accepts
+     * (RocksDBOptions.MEMTABLE_SIZE), which an auto-sized budget under 1 GiB 
would
+     * otherwise fall under.
+     */
+    public static long writeBufferSize(long totalMemory) {
+        return Math.max(totalMemory / 1000, MIB);
+    }
+
+    private static long jvmMemory() {
+        try {
+            // Reports the cgroup v1/v2 memory limit inside a container, but 
older JDK 17
+            // updates may not see a limit set only on a parent cgroup
+            OperatingSystemMXBean os = ManagementFactory.getPlatformMXBean(
+                    OperatingSystemMXBean.class);
+            return os == null ? -1L : os.getTotalMemorySize();
+        } catch (RuntimeException | LinkageError e) {
+            log.warn("Failed to read physical memory size", e);
+            return -1L;
+        }
+    }
+
+    /**
+     * A cgroup memory limit in bytes (-1 for none), and whether the mounts 
may hide a
+     * stricter one: a cgroup mount existed but none contained this process's 
cgroup, or
+     * every matching cgroup2 mount was a subtree, so bytes only covers what 
is visible
+     * from those mounts' roots down.
+     */
+    static final class CgroupLimit {
+
+        final long bytes;
+        final boolean incomplete;
+
+        CgroupLimit(long bytes, boolean incomplete) {
+            this.bytes = bytes;
+            this.incomplete = incomplete;
+        }
+    }
+
+    /**
+     * The smaller of what the JVM reports and the cgroup limit, ignoring 
unknown (<= 0)
+     * values.
+     */
+    static long effectivePhysical(long jvm, long cgroup) {
+        if (cgroup <= 0) {
+            return jvm;
+        }
+        return jvm <= 0 ? cgroup : Math.min(jvm, cgroup);
+    }
+
+    /**
+     * The lowest memory limit on this process's cgroup or any visible 
ancestor, or -1
+     * when there is none or it can't be read. The membership path from 
/proc/self/cgroup
+     * is rebased onto every mount of the controller in /proc/self/mountinfo 
whose root
+     * contains it, so a cgroupfs mounted from a subtree (root /kubepods at 
/sys/fs/cgroup)
+     * is walked from the right directory, and the lowest limit over all those 
mounts is
+     * taken: a leaf-only or unrelated mount listed first can't hide a fuller 
view listed
+     * later. Without a matching mount the default root is used. cgroup v2
+     * walks memory.max from the process's cgroup up to the mount; cgroup v1 
reads
+     * hierarchical_memory_limit, which already accounts for ancestors. A 
limit above the
+     * mount root, as inside a private cgroup namespace, stays invisible.
+     */
+    static long cgroupMemoryLimit(Path procSelfCgroup, Path mountinfo, Path 
defaultRoot) {
+        return cgroupLimit(procSelfCgroup, mountinfo, defaultRoot).bytes;
+    }
+
+    static CgroupLimit cgroupLimit(Path procSelfCgroup, Path mountinfo, Path 
defaultRoot) {
+        List<String[]> v2Mounts = cgroupMounts(mountinfo, true);
+        List<String[]> v1Mounts = cgroupMounts(mountinfo, false);
+        List<String> lines;
+        try {
+            lines = Files.readAllLines(procSelfCgroup, StandardCharsets.UTF_8);
+        } catch (IOException | RuntimeException e) {
+            return new CgroupLimit(-1L, false);
+        }
+        long limit = -1L;
+        boolean incomplete = false;
+        for (String line : lines) {
+            String[] parts = line.split(":", 3);
+            if (parts.length < 3) {
+                continue;
+            }
+            boolean v2 = parts[0].equals("0") && parts[1].isEmpty();
+            if (!v2 && !("," + parts[1] + ",").contains(",memory,")) {
+                continue;
+            }
+            List<String[]> mounts = v2 ? v2Mounts : v1Mounts;
+            boolean matched = false;
+            boolean fullView = false;
+            for (String[] mount : mounts) {
+                if (!contains(mount[0], parts[2])) {
+                    // A mount of another subtree says nothing about this 
cgroup
+                    continue;
+                }
+                matched = true;
+                Path point = Paths.get(mount[1]);
+                String relative = rebase(parts[2], mount[0]);
+                // A full-hierarchy mount only covers the ancestors if this 
process's own
+                // directory is actually reachable through it
+                fullView |= mount[0].equals("/") && visible(point, relative);

Review Comment:
   Agreed, fixed in 7a1af80a2. When the process's cgroup2 path is `/` and no 
finite `memory.max` is visible, the result is now flagged incomplete, so 
auto-sizing logs the explicit-budget warning instead of treating `max` as 
unlimited. That's the namespace-root view you describe, where the mount is also 
rooted at `/`. A finite limit visible at the namespace root still applies 
without a flag, and v1 isn't flagged, since `hierarchical_memory_limit` already 
covers the ancestors. One side effect: a process genuinely in the host's root 
cgroup with no limit also gets the warning; that should be rare, since services 
run in slices. New regression `testNamespaceRootViewWithoutLimitIsFlagged` 
covers v2 with `max` (flagged) and with 2 GiB (applied), plus the v1 control; 
with the new check removed it fails. Store core tests: 135 passed.



##########
hugegraph-store/docs/deployment-guide.md:
##########
@@ -356,14 +356,54 @@ rocksdb:
   level0_file_num_compaction_trigger: 4
   max_background_jobs: 8                # Background compaction/flush threads
 
-  # Block Cache
-  block_cache_size: 16000000000         # Block cache (16GB)
+  # Budget split: this share goes to memtables, the rest to the block cache
+  write_buffer_ratio: 0.66
 
   # SST File Size
   target_file_size_base: 134217728      # Target SST size (128MB)
   max_bytes_for_level_base: 1073741824  # L1 size (1GB)
 ```
 
+`total_memory_size` bounds the memtables (`write_buffer_ratio` of it) and the 
block cache
+(the rest). Both live outside the Java heap, so `-Xmx` does not limit them. A 
fixed 1 GiB
+cache for the Raft log comes on top of this budget.
+
+With `total_memory_size: 0`, or the key unset, the Store sizes the budget at 
startup as half
+of what is left after the heap, the maximum direct memory and a 1.5 GiB 
reserve, clamped to
+256 MiB–32 GB. Inside a container the starting point is the cgroup memory 
limit, including a
+limit set only on a parent cgroup when the Store can see that cgroup; inside a 
private cgroup
+namespace, or when only a subtree of the cgroup2 hierarchy is mounted, a limit 
above it is not
+visible, so pin the value there if only the pod or slice is limited (the Store 
logs a warning
+when it detects such a mount). A Store with a 4 GiB limit, `-Xmx1g` and 
`-XX:MaxDirectMemorySize=512m` gets 512 MiB. Without
+`-XX:MaxDirectMemorySize` the JVM allows as much direct memory as heap, and 
the budget counts
+it that way. `bin/start-hugegraph-store.sh` sets the flag to the heap it 
picks; when `-j` sets
+`-Xmx`, `-XX:MaxHeapSize` or `-XX:MaxDirectMemorySize` itself, the launcher 
leaves the flag out and the JVM's
+default (that heap) or the given cap applies. Either way the budget counts a 
limit the JVM
+enforces. In small containers set a
+cap below the heap, or the budget falls to the 256 MiB floor.
+
+On a host without a container limit the starting point is physical memory. The 
default
+`bin/start-hugegraph-store.sh` caps the heap at 2 GiB and direct memory at the 
same 2 GiB, so a
+16 GiB host gets about 5.25 GiB. When you raise the heap, pass a direct-memory 
cap with it,
+for example `-j "-Xmx36g -XX:MaxDirectMemorySize=2g"`; otherwise direct memory 
counts as a
+second heap. With a 2 GiB cap a 16 GiB host with `-Xmx8g` gets 2.25 GiB and a 
64 GiB host with
+`-Xmx36g` gets 12.25 GiB. Before this default every host got a fixed 
`32000000000`, so pin the
+value after upgrading if a large node relied on it.
+
+The chosen value is logged by `RocksdbMemoryBudget` at startup, with a warning 
when the floor
+applies, or when an explicit value is under 256 MiB or exceeds the memory left 
after the heap,
+direct memory and the reserve. Set a number of bytes, at least 1048576 (1 
MiB), to pin it; a
+smaller value or a unit suffix such as `4GB` is rejected. Before this default 
existed the
+shipped value was `32000000000`, which can exceed a container limit and get 
the Store
+OOM-killed. Both caps are soft: RocksDB can briefly go over them under heavy 
writes, and a
+small budget with many partitions means frequent memtable flushes.
+
+**Upgrading an existing deployment.** Auto-sizing applies only when the loaded 
configuration
+has `total_memory_size: 0` or no value. A Store that mounts its own 
`conf/application-pd.yml`,

Review Comment:
   Fixed in 7a1af80a2. The upgrade note now explains the copy PD keeps. When PD 
has none yet, the first Store to start uploads its local `application-pd.yml` 
(KV key `S:FS`), and any Store whose local file isn't newer than `S:Timestamp` 
loads it and writes it over its local file. So updating the Store package or a 
local file doesn't help while PD's copy still says `32000000000`. Operators 
should set it to `0` or remove it in PD's copy, or set 
`HG_STORE_ROCKSDB_TOTAL_MEMORY_SIZE` / `-Drocksdb.total_memory_size` on every 
Store, which the Store keeps above PD's copy.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to