cmccabe commented on code in PR #14628:
URL: https://github.com/apache/kafka/pull/14628#discussion_r1373812595


##########
metadata/src/main/java/org/apache/kafka/metadata/properties/MetaPropertiesEnsemble.java:
##########
@@ -0,0 +1,497 @@
+/*
+ * 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.kafka.metadata.properties;
+
+import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.Uuid;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.nio.file.NoSuchFileException;
+import java.util.AbstractMap.SimpleImmutableEntry;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Properties;
+import java.util.Random;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.function.BiConsumer;
+
+/**
+ * A collection of meta.properties information for Kafka log directories.
+ *
+ * Directories are categorized into empty, error, and normal. Each directory 
must appear in only
+ * one category, corresponding to emptyLogDirs, errorLogDirs, and logDirProps.
+ *
+ * This class is immutable. Modified copies can be made with the Copier class.
+ */
+public class MetaPropertiesEnsemble {
+    /**
+     * The log4j object for this class.
+     */
+    private static final Logger LOG = 
LoggerFactory.getLogger(MetaPropertiesEnsemble.class);
+
+    /**
+     * A completely empty MetaPropertiesEnsemble object.
+     */
+    public static final MetaPropertiesEnsemble EMPTY = new 
MetaPropertiesEnsemble(Collections.emptySet(),
+        Collections.emptySet(),
+        Collections.emptyMap(),
+        Optional.empty());
+
+    /**
+     * The name of the meta.properties file within each log directory.
+     */
+    public static final String META_PROPERTIES_NAME = "meta.properties";
+
+    /**
+     * The set of log dirs that were empty.
+     */
+    private final Set<String> emptyLogDirs;
+
+    /**
+     * The set of log dirs that had errors.
+     */
+    private final Set<String> errorLogDirs;
+
+    /**
+     * A map from log directories to the meta.properties information inside 
each one.
+     */
+    private final Map<String, MetaProperties> logDirProps;
+
+    /**
+     * The metadata log directory, or the empty string if there is none.
+     */
+    private final Optional<String> metadataLogDir;
+
+    /**
+     * Utility class for loading a MetaPropertiesEnsemble from the disk.
+     */
+    public static class Loader {
+        private final TreeSet<String> logDirs = new TreeSet<>();
+        private Optional<String> metadataLogDir = Optional.empty();
+
+        public Loader addLogDirs(Collection<String> logDirs) {
+            for (String logDir : logDirs) {
+                this.logDirs.add(logDir);
+            }
+            return this;
+        }
+
+        public Loader addLogDir(String logDir) {
+            this.logDirs.add(logDir);
+            return this;
+        }
+
+        public Loader addMetadataLogDir(String metadataLogDir) {
+            if (this.metadataLogDir.isPresent()) {
+                throw new RuntimeException("Cannot specify more than one 
metadata log directory. " +
+                    "Already specified " + this.metadataLogDir.get());
+            }
+            this.metadataLogDir = Optional.of(metadataLogDir);
+            logDirs.add(metadataLogDir);
+            return this;
+        }
+
+        public MetaPropertiesEnsemble load() throws IOException  {
+            if (logDirs.isEmpty()) {
+                throw new RuntimeException("You must specify at least one log 
directory.");
+            }
+            Set<String> emptyLogDirs = new HashSet<>();
+            Set<String> errorLogDirs = new HashSet<>();
+            Map<String, MetaProperties> logDirProps = new HashMap<>();
+            for (String logDir : logDirs) {
+                String metaPropsFile = new File(logDir, 
META_PROPERTIES_NAME).getAbsolutePath();
+                try {
+                    Properties props = 
PropertiesUtils.readPropertiesFile(metaPropsFile);
+                    MetaProperties meta = new 
MetaProperties.Builder(props).build();
+                    logDirProps.put(logDir, meta);
+                } catch (NoSuchFileException | FileNotFoundException e) {
+                    emptyLogDirs.add(logDir);
+                } catch (Exception e) {
+                    LOG.error("Error while reading meta.properties file {}", 
metaPropsFile, e);
+                    errorLogDirs.add(logDir);
+                }
+            }
+            return new MetaPropertiesEnsemble(emptyLogDirs, errorLogDirs, 
logDirProps, metadataLogDir);
+        }
+    }
+
+    /**
+     * Utility class for copying a MetaPropertiesEnsemble object, possibly 
with changes.
+     */
+    public static class Copier {
+        private final MetaPropertiesEnsemble prev;
+        private Random random = new Random();
+        private Set<String> emptyLogDirs;
+        private Set<String> errorLogDirs;
+        private Map<String, MetaProperties> logDirProps;
+        private Optional<String> metaLogDir;
+
+        public Copier(MetaPropertiesEnsemble prev) {
+            this.prev = prev;
+            this.emptyLogDirs = new HashSet<>(prev.emptyLogDirs());
+            this.errorLogDirs = new HashSet<>(prev.errorLogDirs());
+            this.logDirProps = new HashMap<>(prev.logDirProps());
+            this.metaLogDir = prev.metadataLogDir;
+        }
+
+        /**
+         * Set the Random object to use for generating IDs.
+         *
+         * @param random    The Random object to use for generating IDs.
+         * @return          This copier
+         */
+        public Copier setRandom(Random random) {
+            this.random = random;
+            return this;
+        }
+
+        /**
+         * Access the mutable empty log directories set.
+         *
+         * @return          The mutable empty log directories set.
+         */
+        public Set<String> emptyLogDirs() {
+            return emptyLogDirs;
+        }
+
+        /**
+         * Access the mutable error log directories set.
+         *
+         * @return          The mutable error log directories set.
+         */
+        public Set<String> errorLogDirs() {
+            return errorLogDirs;
+        }
+
+        /**
+         * Access the mutable logDirProps map.
+         *
+         * @return          The mutable error log directories map.
+         */
+        public Map<String, MetaProperties> logDirProps() {
+            return logDirProps;
+        }
+
+        /**
+         * Generate a random directory ID that is safe and not used by any 
other directory.
+         *
+         * @return          A new random directory ID.
+         */
+        public Uuid generateValidDirectoryId() {
+            while (true) {
+                Uuid uuid = new Uuid(random.nextLong(), random.nextLong());
+                if (uuid.isSafe()) {
+                    boolean duplicate = false;
+                    for (MetaProperties metaProps : logDirProps.values()) {
+                        if (metaProps.directoryId().equals(Optional.of(uuid))) 
{
+                            duplicate = true;
+                            break;
+                        }
+                    }
+                    if (!duplicate) {
+                        return uuid;
+                    }
+                }
+            }
+        }
+
+        /**
+         * Verify that we have set up the Copier correctly.
+         *
+         * @throws RuntimeException if a directory appears in more than one 
category.
+         */
+        public void verify() {
+            for (String logDir : emptyLogDirs) {
+                if (errorLogDirs.contains(logDir)) {
+                    throw new RuntimeException("Error: log directory " + 
logDir +
+                        " is in both emptyLogDirs and errorLogDirs.");
+                }
+                if (logDirProps.containsKey(logDir)) {
+                    throw new RuntimeException("Error: log directory " + 
logDir +
+                        " is in both emptyLogDirs and logDirProps.");
+                }
+            }
+            for (String logDir : errorLogDirs) {
+                if (logDirProps.containsKey(logDir)) {
+                    throw new RuntimeException("Error: log directory " + 
logDir +
+                            " is in both errorLogDirs and logDirProps.");
+                }
+            }
+        }
+
+        /**
+         * Write any changed log directories out to disk.
+         */
+        public void writeLogDirChanges() {
+            writeLogDirChanges((metaPropsPath, e) -> {
+                LOG.error("Error while writing meta.properties file {}", 
metaPropsPath, e);
+            });
+        }
+
+        /**
+         * Write any changed log directories out to disk.
+         *
+         * @param errorHandler  A handler that will be called with (logDir, 
exception) any time we
+         *                      hit an exception writing out a meta.properties 
file.
+         */
+        public void writeLogDirChanges(BiConsumer<String, Exception> 
errorHandler) {
+            Map<String, MetaProperties> newOrChanged = new HashMap<>();
+            HashSet<String> newSet = new HashSet<>();
+            for (Entry<String, MetaProperties> entry : 
prev.logDirProps().entrySet()) {
+                MetaProperties metaProps = entry.getValue();
+                MetaProperties prevMetaProps = logDirProps.get(entry.getKey());
+                if (!metaProps.equals(prevMetaProps)) {
+                    newOrChanged.put(entry.getKey(), entry.getValue());
+                }
+            }
+            for (Entry<String, MetaProperties> entry : logDirProps.entrySet()) 
{
+                if (!prev.logDirProps.containsKey(entry.getKey())) {
+                    newOrChanged.put(entry.getKey(), entry.getValue());
+                    newSet.add(entry.getKey());
+                }
+            }
+            for (Entry<String, MetaProperties> entry : 
newOrChanged.entrySet()) {
+                String logDir = entry.getKey();
+                String metaPropsPath = new File(logDir, 
META_PROPERTIES_NAME).getAbsolutePath();
+                try {
+                    
PropertiesUtils.writePropertiesFile(entry.getValue().toProperties(), 
metaPropsPath);
+                    LOG.info("Wrote out {} meta.properties file {} containing 
{}",
+                            newSet.contains(entry.getKey()) ? "new" : 
"changed",
+                            entry.getKey(), entry.getValue());
+                } catch (Exception e) {

Review Comment:
   ok



-- 
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: jira-unsubscr...@kafka.apache.org

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

Reply via email to