You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ozone.apache.org by GitBox <gi...@apache.org> on 2022/05/24 11:56:44 UTC

[GitHub] [ozone] kerneltime commented on a diff in pull request #3426: HDDS-5821 Container cache management for closing RockDB

kerneltime commented on code in PR #3426:
URL: https://github.com/apache/ozone/pull/3426#discussion_r880411930


##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/db/RocksDatabase.java:
##########
@@ -0,0 +1,490 @@
+/*
+ * 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.hadoop.hdds.utils.db;
+
+import org.apache.hadoop.hdds.utils.HddsServerUtil;
+import org.rocksdb.Checkpoint;
+import org.rocksdb.ColumnFamilyDescriptor;
+import org.rocksdb.ColumnFamilyHandle;
+import org.rocksdb.DBOptions;
+import org.rocksdb.FlushOptions;
+import org.rocksdb.Holder;
+import org.rocksdb.Options;
+import org.rocksdb.ReadOptions;
+import org.rocksdb.RocksDB;
+import org.rocksdb.RocksDBException;
+import org.rocksdb.RocksIterator;
+import org.rocksdb.TransactionLogIterator;
+import org.rocksdb.WriteBatch;
+import org.rocksdb.WriteOptions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.apache.hadoop.hdds.StringUtils.bytes2String;
+
+/**
+ * A wrapper class for {@link RocksDB}.
+ * When there is a {@link RocksDBException},
+ * this class will close the underlying {@link org.rocksdb.RocksObject}s.
+ */
+public final class RocksDatabase implements Closeable {
+  static final Logger LOG = LoggerFactory.getLogger(RocksDatabase.class);
+
+  static final String ESTIMATE_NUM_KEYS = "rocksdb.estimate-num-keys";
+
+  /**
+   * Read DB and return existing column families.
+   *
+   * @return List of column families
+   * @throws RocksDBException on Error.
+   */
+  private static List<TableConfig> getColumnFamilies(File file)
+      throws RocksDBException {
+    final List<TableConfig> columnFamilies = RocksDB.listColumnFamilies(
+            new Options(), file.getAbsolutePath())
+        .stream()
+        .map(TableConfig::newTableConfig)
+        .collect(Collectors.toList());
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("Found column families in DB {}: {}", file, columnFamilies);
+    }
+    return columnFamilies;
+  }
+
+  static RocksDatabase open(File dbFile, DBOptions dbOptions,
+      WriteOptions writeOptions, Set<TableConfig> families,
+      boolean readOnly) throws IOException {
+    List<ColumnFamilyDescriptor> descriptors = null;
+    RocksDB db = null;
+    final Map<String, ColumnFamily> columnFamilies = new HashMap<>();
+    try {
+      // This logic has been added to support old column families that have
+      // been removed, or those that may have been created in a future version.
+      // TODO : Revisit this logic during upgrade implementation.
+      final Stream<TableConfig> extra = getColumnFamilies(dbFile).stream()
+          .filter(extraColumnFamily(families));
+      descriptors = Stream.concat(families.stream(), extra)
+          .map(TableConfig::getDescriptor)
+          .collect(Collectors.toList());
+
+      // open RocksDB
+      final List<ColumnFamilyHandle> handles = new ArrayList<>();
+      if (readOnly) {
+        db = RocksDB.openReadOnly(dbOptions, dbFile.getAbsolutePath(),
+            descriptors, handles);
+      } else {
+        db = RocksDB.open(dbOptions, dbFile.getAbsolutePath(),
+            descriptors, handles);
+      }
+      // init a column family map.
+      for (ColumnFamilyHandle h : handles) {
+        final ColumnFamily f = new ColumnFamily(h);
+        columnFamilies.put(f.getName(), f);
+      }
+      return new RocksDatabase(dbFile, db, dbOptions, writeOptions,
+          descriptors, Collections.unmodifiableMap(columnFamilies));
+    } catch (RocksDBException e) {
+      close(columnFamilies, db, descriptors, writeOptions, dbOptions);
+      throw HddsServerUtil.toIOException("open " + dbFile, e);
+    }
+  }
+
+  private static void close(ColumnFamilyDescriptor d) {
+    runWithTryCatch(() -> d.getOptions().close(), new Object() {
+      @Override
+      public String toString() {
+        return d.getClass() + ":" + bytes2String(d.getName());
+      }
+    });
+  }
+
+  private static void close(Map<String, ColumnFamily> columnFamilies,
+      RocksDB db, List<ColumnFamilyDescriptor> descriptors,
+      WriteOptions writeOptions, DBOptions dbOptions) {
+    if (columnFamilies != null) {
+      for (ColumnFamily f : columnFamilies.values()) {
+        runWithTryCatch(() -> f.getHandle().close(), f);
+      }
+    }
+
+    if (db != null) {
+      runWithTryCatch(db::close, "db");
+    }
+
+    if (descriptors != null) {
+      descriptors.forEach(RocksDatabase::close);
+    }
+
+    if (writeOptions != null) {
+      runWithTryCatch(writeOptions::close, "writeOptions");
+    }
+    if (dbOptions != null) {
+      runWithTryCatch(dbOptions::close, "dbOptions");
+    }
+  }
+
+  private static void runWithTryCatch(Runnable runnable, Object name) {
+    try {
+      runnable.run();
+    } catch (Throwable t) {
+      LOG.error("Failed to close " + name, t);
+    }
+  }
+
+  static Predicate<TableConfig> extraColumnFamily(Set<TableConfig> families) {
+    return f -> {
+      if (families.contains(f)) {
+        return false;
+      }
+      LOG.info("Found an extra column family in existing DB: {}", f);
+      return true;
+    };
+  }
+
+  public boolean isClosed() {
+    return isClosed.get();
+  }
+
+  /**
+   * Represents a checkpoint of the db.
+   *
+   * @see Checkpoint
+   */
+  final class RocksCheckpoint {
+    private final Checkpoint checkpoint;
+
+    private RocksCheckpoint() {
+      this.checkpoint = Checkpoint.create(db);
+    }
+
+    public void createCheckpoint(Path path) throws IOException {
+      try {
+        checkpoint.createCheckpoint(path.toString());
+      } catch (RocksDBException e) {
+        closeOnError(e);
+        throw toIOException("createCheckpoint " + path, e);
+      }
+    }
+
+    public long getLatestSequenceNumber() {
+      return RocksDatabase.this.getLatestSequenceNumber();
+    }
+  }
+
+  /**
+   * Represents a column family of the db.
+   *
+   * @see ColumnFamilyHandle
+   */
+  public static final class ColumnFamily {
+    private final byte[] nameBytes;
+    private final String name;
+    private final ColumnFamilyHandle handle;
+
+    public ColumnFamily(ColumnFamilyHandle handle) throws RocksDBException {
+      this.nameBytes = handle.getName();
+      this.name = bytes2String(nameBytes);
+      this.handle = handle;
+      LOG.debug("new ColumnFamily for {}", name);
+    }
+
+    public String getName() {
+      return name;
+    }
+
+    public String getName(StringCodec codec) {
+      return codec.fromPersistedFormat(nameBytes);
+    }
+
+    private ColumnFamilyHandle getHandle() {
+      return handle;
+    }
+
+    public int getID() {
+      return getHandle().getID();
+    }
+
+    public void batchDelete(WriteBatch writeBatch, byte[] key)
+        throws IOException {
+      try {
+        writeBatch.delete(getHandle(), key);

Review Comment:
   @jojochuang I will be filling additional PRs to address remaining leaks. This PR is to get the RocksDatabase.java abstraction in and address the cache handling for it.



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org