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


##########
hugegraph-store/hg-store-core/src/main/java/org/apache/hugegraph/store/options/RocksdbMemoryBudget.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * 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.lang.management.ManagementFactory;
+
+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;
+    // Direct memory counted when -XX:MaxDirectMemorySize is unset. The JVM 
then allows
+    // as much as the heap, but the Store's gRPC/Netty buffers do not grow 
with the heap,
+    // and counting a 36 GB heap twice would leave rocksdb the floor on a 
large host
+    static final long UNSET_DIRECT = 1024 * 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();
+        long physical = physicalMemory();
+        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);
+            }
+            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 (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 physicalMemory() {
+        try {
+            // Reports the cgroup v1/v2 memory limit inside a container; 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();

Review Comment:
   Fixed in 03a4d4367 by detecting it rather than requiring a JDK update. 
`RocksdbMemoryBudget` now reads the cgroup itself: on v2 it walks `memory.max` 
from the process's cgroup (from `/proc/self/cgroup`) up to the mount root, on 
v1 it reads `hierarchical_memory_limit`, which already includes ancestors. It 
uses the lower of that and what the JVM reports. New tests build fake v1 and v2 
trees, including your case: a 64 GiB host reported by the JVM, `-Xmx1g`, a 512 
MiB direct cap and a 4 GiB limit only on the pod now gives 512 MiB. One limit 
remains: inside a private cgroup namespace the mount root is the container's 
own cgroup, so a limit above it can't be seen from inside. The deployment guide 
says so and tells users to pin the value in that setup.



##########
hugegraph-store/docs/deployment-guide.md:
##########
@@ -726,8 +751,15 @@ environment:
   HG_STORE_REST_PORT: "8520"                           # maps to server.port
   HG_STORE_RAFT_ADDRESS: store0:8510                   # maps to raft.address
   HG_STORE_DATA_PATH: /hugegraph-store/storage         # maps to app.data-path
+  # optional; maps to rocksdb.total_memory_size (bytes); unset = config file 
or auto-size
+  # HG_STORE_ROCKSDB_TOTAL_MEMORY_SIZE: "2147483648"
 ```
 
+`HG_STORE_ROCKSDB_TOTAL_MEMORY_SIZE` must be a plain number of bytes; the 
entrypoint refuses
+anything else. When set it outranks `rocksdb.total_memory_size` in a mounted
+`conf/application-pd.yml` and a `-Drocksdb.total_memory_size` in `JAVA_OPTS`. 
Leave it unset to let the Store size the budget from the container

Review Comment:
   Added in 03a4d4367: the guide has an "Upgrading an existing deployment" step 
(set `total_memory_size` to 0 or remove it, or set 
`HG_STORE_ROCKSDB_TOTAL_MEMORY_SIZE`), and this paragraph now says that leaving 
the variable unset only auto-sizes when the loaded config is also 0 or unset. 
The Store also logs a WARN when it sees exactly `32000000000`, the old shipped 
value, telling the operator to set it to 0 or remove it.



##########
.github/workflows/pd-store-ci.yml:
##########
@@ -406,6 +406,10 @@ jobs:
         run: |
           mvn editorconfig:check -pl hugegraph-store/hg-store-test -am -ntp
 
+      - name: Run Store docker entrypoint rocksdb memory tests

Review Comment:
   Fixed in 3fb0da01f: `test-store-docker-entrypoint.sh` maps to `{"store"}` in 
`CONTRACT_SUITES`, and 
`test_contract_scripts_reach_their_actual_inner_jobs_and_steps` now covers it, 
checking the `store` job's condition and that the step has no `if:` of its own. 
With the mapping removed, that test fails for this script.



-- 
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