index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/LedgerUnderreplicationManager.java
/* * 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.bookkeeper.meta; import com.google.common.collect.Lists; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Predicate; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback; import org.apache.bookkeeper.replication.ReplicationException; /** * Interface for marking ledgers which need to be rereplicated. */ public interface LedgerUnderreplicationManager extends AutoCloseable { /** * Mark a ledger as underreplicated. The replication should * then check which fragments are underreplicated and rereplicate them */ default void markLedgerUnderreplicated(long ledgerId, String missingReplica) throws ReplicationException { FutureUtils.result( markLedgerUnderreplicatedAsync( ledgerId, Lists.newArrayList(missingReplica)), ReplicationException.EXCEPTION_HANDLER); } /** * Check whether the ledger is being replicated by any bookie. */ boolean isLedgerBeingReplicated(long ledgerId) throws ReplicationException; /** * Mark a ledger as underreplicated with missing bookies. The replication should then * check which fragements are underreplicated and rereplicate them. * * @param ledgerId ledger id * @param missingReplicas missing replicas * @return a future presents the mark result. */ CompletableFuture<Void> markLedgerUnderreplicatedAsync(long ledgerId, Collection<String> missingReplicas); /** * Mark a ledger as fully replicated. If the ledger is not * already marked as underreplicated, this is a noop. */ void markLedgerReplicated(long ledgerId) throws ReplicationException.UnavailableException; /** * Get the UnderreplicatedLedger info if this ledger is marked * underreplicated otherwise it returns null. * * @param ledgerId * ledger id * @return the UnderreplicatedLedger info instance if this ledger is marked * underreplicated otherwise it returns null. * @throws ReplicationException.UnavailableException */ UnderreplicatedLedger getLedgerUnreplicationInfo(long ledgerId) throws ReplicationException.UnavailableException; /** * Get a list of all the underreplicated ledgers which have been * marked for rereplication, filtered by the predicate on the missing replicas list. * * <p>Missing replicas list of an underreplicated ledger is the list of the bookies which are part of * the ensemble of this ledger and are currently unavailable/down. * * @param predicate filter to use while listing under replicated ledgers. 'null' if filtering is not required * @return an iterator which returns underreplicated ledgers. */ Iterator<UnderreplicatedLedger> listLedgersToRereplicate(Predicate<List<String>> predicate); /** * Acquire a underreplicated ledger for rereplication. The ledger * should be locked, so that no other agent will receive the ledger * from this call. * The ledger should remain locked until either #markLedgerComplete * or #releaseLedger are called. * This call is blocking, so will not return until a ledger is * available for rereplication. */ long getLedgerToRereplicate() throws ReplicationException.UnavailableException; /** * Poll for a underreplicated ledger to rereplicate. * @see #getLedgerToRereplicate * @return the ledgerId, or -1 if none are available */ long pollLedgerToRereplicate() throws ReplicationException.UnavailableException; void acquireUnderreplicatedLedger(long ledgerId) throws ReplicationException; /** * Release a previously acquired ledger. This allows others to acquire the ledger. */ void releaseUnderreplicatedLedger(long ledgerId) throws ReplicationException.UnavailableException; /** * Release all resources held by the ledger underreplication manager. */ @Override void close() throws ReplicationException.UnavailableException; /** * Stop ledger replication. Currently running ledger rereplication tasks * will be continued and will be stopped from next task. This will block * ledger replication {@link #Auditor} and {@link #getLedgerToRereplicate()} * tasks. */ void disableLedgerReplication() throws ReplicationException.UnavailableException; /** * Resuming ledger replication. This will allow ledger replication * {@link #Auditor} and {@link #getLedgerToRereplicate()} tasks to continue. */ void enableLedgerReplication() throws ReplicationException.UnavailableException; /** * Check whether the ledger replication is enabled or not. This will return * true if the ledger replication is enabled, otherwise return false. * * @return - return true if it is enabled otherwise return false */ boolean isLedgerReplicationEnabled() throws ReplicationException.UnavailableException; /** * Receive notification asynchronously when the ledger replication process * is enabled. * * @param cb * - callback implementation to receive the notification */ void notifyLedgerReplicationEnabled(GenericCallback<Void> cb) throws ReplicationException.UnavailableException; /** * Creates the zNode for lostBookieRecoveryDelay with the specified value and returns true. * If the node is already existing, then it returns false. * * @param lostBookieRecoveryDelay * @return * true if it succeeds in creating zNode for lostBookieRecoveryDelay, false if it is already existing * @throws ReplicationException.UnavailableException */ boolean initializeLostBookieRecoveryDelay(int lostBookieRecoveryDelay) throws ReplicationException.UnavailableException; /** * Setter for the lostBookieRecoveryDelay znode. * * @param lostBookieRecoveryDelay * @throws ReplicationException.UnavailableException */ void setLostBookieRecoveryDelay(int lostBookieRecoveryDelay) throws ReplicationException.UnavailableException; /** * Getter for the lostBookieRecoveryDelay. * * @return the int value of lostBookieRecoveryDelay * @throws ReplicationException.UnavailableException */ int getLostBookieRecoveryDelay() throws ReplicationException.UnavailableException; /** * Setter for the CheckAllLedgers last executed ctime. * * @param checkAllLedgersCTime * @throws ReplicationException.UnavailableException */ void setCheckAllLedgersCTime(long checkAllLedgersCTime) throws ReplicationException.UnavailableException; /** * Getter for the CheckAllLedgers last executed ctime. * * @return the long value of checkAllLedgersCTime * @throws ReplicationException.UnavailableException */ long getCheckAllLedgersCTime() throws ReplicationException.UnavailableException; /** * Setter for the PlacementPolicyCheck last executed ctime. * * @param placementPolicyCheckCTime * @throws ReplicationException.UnavailableException */ void setPlacementPolicyCheckCTime(long placementPolicyCheckCTime) throws ReplicationException.UnavailableException; /** * Getter for the PlacementPolicyCheck last executed ctime. * * @return the long value of placementPolicyCheckCTime * @throws ReplicationException.UnavailableException */ long getPlacementPolicyCheckCTime() throws ReplicationException.UnavailableException; /** * Setter for the ReplicasCheck last executed ctime. * * @param replicasCheckCTime * @throws ReplicationException.UnavailableException */ void setReplicasCheckCTime(long replicasCheckCTime) throws ReplicationException.UnavailableException; /** * Getter for the ReplicasCheck last executed ctime. * * @return the long value of replicasCheckCTime * @throws ReplicationException.UnavailableException */ long getReplicasCheckCTime() throws ReplicationException.UnavailableException; /** * Receive notification asynchronously when the num of under-replicated ledgers Changed. * * @param cb * @throws ReplicationException.UnavailableException */ @Deprecated default void notifyUnderReplicationLedgerChanged(GenericCallback<Void> cb) throws ReplicationException.UnavailableException {} /** * Receive notification asynchronously when the lostBookieRecoveryDelay value is Changed. * * @param cb * @throws ReplicationException.UnavailableException */ void notifyLostBookieRecoveryDelayChanged(GenericCallback<Void> cb) throws ReplicationException.UnavailableException; /** * If a replicationworker has acquired lock on an underreplicated ledger, * then getReplicationWorkerIdRereplicatingLedger should return * ReplicationWorkerId (BookieId) of the ReplicationWorker that is holding * lock. If lock for the underreplicated ledger is not yet acquired or if it * is released then it is supposed to return null. * * @param ledgerId * @return * @throws ReplicationException.UnavailableException */ String getReplicationWorkerIdRereplicatingLedger(long ledgerId) throws ReplicationException.UnavailableException; }
200
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/LongHierarchicalLedgerManager.java
/* * 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.bookkeeper.meta; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import org.apache.bookkeeper.conf.AbstractConfiguration; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.Processor; import org.apache.bookkeeper.util.StringUtils; import org.apache.bookkeeper.util.ZkUtils; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.AsyncCallback.VoidCallback; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooKeeper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * LongHierarchical Ledger Manager which manages ledger meta in zookeeper using 5-level hierarchical znodes. * * <p>LongHierarchicalLedgerManager splits the generated id into 5 parts (3-4-4-4-4): * * <pre> * &lt;level0 (3 digits)&gt;&lt;level1 (4 digits)&gt;&lt;level2 (4 digits)&gt;&lt;level3 (4 digits)&gt; * &lt;level4 (4 digits)&gt; * </pre> * * <p>These 5 parts are used to form the actual ledger node path used to store ledger metadata: * * <pre> * (ledgersRootPath) / level0 / level1 / level2 / level3 / L(level4) * </pre> * * <p>E.g Ledger 0000000000000000001 is split into 5 parts <i>000</i>, <i>0000</i>, <i>0000</i>, <i>0000</i>, * <i>0001</i>, which is stored in <i>(ledgersRootPath)/000/0000/0000/0000/L0001</i>. So each znode could have at most * 10000 ledgers, which avoids errors during garbage collection due to lists of children that are too long. */ class LongHierarchicalLedgerManager extends AbstractHierarchicalLedgerManager { static final Logger LOG = LoggerFactory.getLogger(LongHierarchicalLedgerManager.class); static final String IDGEN_ZNODE = "idgen-long"; /** * Constructor. * * @param conf * Configuration object * @param zk * ZooKeeper Client Handle */ public LongHierarchicalLedgerManager(AbstractConfiguration conf, ZooKeeper zk) { super(conf, zk); } @Override public long getLedgerId(String pathName) throws IOException { if (!pathName.startsWith(ledgerRootPath)) { throw new IOException("it is not a valid hashed path name : " + pathName); } String hierarchicalPath = pathName.substring(ledgerRootPath.length() + 1); return StringUtils.stringToLongHierarchicalLedgerId(hierarchicalPath); } @Override public String getLedgerPath(long ledgerId) { return ledgerRootPath + StringUtils.getLongHierarchicalLedgerPath(ledgerId); } // // Active Ledger Manager // @Override public void asyncProcessLedgers(final Processor<Long> processor, final AsyncCallback.VoidCallback finalCb, final Object context, final int successRc, final int failureRc) { // If it succeeds, proceed with our own recursive ledger processing for the 63-bit id ledgers asyncProcessLevelNodes(ledgerRootPath, new RecursiveProcessor(0, ledgerRootPath, processor, context, successRc, failureRc), finalCb, context, successRc, failureRc); } private class RecursiveProcessor implements Processor<String> { private final int level; private final String path; private final Processor<Long> processor; private final Object context; private final int successRc; private final int failureRc; private RecursiveProcessor(int level, String path, Processor<Long> processor, Object context, int successRc, int failureRc) { this.level = level; this.path = path; this.processor = processor; this.context = context; this.successRc = successRc; this.failureRc = failureRc; } @Override public void process(String lNode, VoidCallback cb) { String nodePath = path + "/" + lNode; if ((level == 0) && !isLedgerParentNode(lNode)) { cb.processResult(successRc, null, context); return; } else if (level < 3) { asyncProcessLevelNodes(nodePath, new RecursiveProcessor(level + 1, nodePath, processor, context, successRc, failureRc), cb, context, successRc, failureRc); } else { // process each ledger after all ledger are processed, cb will be call to continue processing next // level4 node asyncProcessLedgersInSingleNode(nodePath, processor, cb, context, successRc, failureRc); } } } @Override public LedgerRangeIterator getLedgerRanges(long zkOpTimeoutMs) { return new LongHierarchicalLedgerRangeIterator(zkOpTimeoutMs); } /** * Iterates recursively through each metadata bucket. */ private class LongHierarchicalLedgerRangeIterator implements LedgerRangeIterator { LedgerRangeIterator rootIterator; final long zkOpTimeoutMs; /** * Returns all children with path as a parent. If path is non-existent, * returns an empty list anyway (after all, there are no children there). * Maps all exceptions (other than NoNode) to IOException in keeping with * LedgerRangeIterator. * * @param path * @return Iterator into set of all children with path as a parent * @throws IOException */ List<String> getChildrenAt(String path) throws IOException { try { List<String> children = ZkUtils.getChildrenInSingleNode(zk, path, zkOpTimeoutMs); Collections.sort(children); return children; } catch (KeeperException.NoNodeException e) { if (LOG.isDebugEnabled()) { LOG.debug("NoNodeException at path {}, assumed race with deletion", path); } return new ArrayList<>(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while reading ledgers at path " + path, ie); } } /** * Represents the ledger range rooted at a leaf node, returns at most one LedgerRange. */ class LeafIterator implements LedgerRangeIterator { // Null iff iteration is complete LedgerRange range; LeafIterator(String path) throws IOException { List<String> ledgerLeafNodes = getChildrenAt(path); Set<Long> ledgerIds = ledgerListToSet(ledgerLeafNodes, path); if (LOG.isDebugEnabled()) { LOG.debug("All active ledgers from ZK for hash node {}: {}", path, ledgerIds); } if (!ledgerIds.isEmpty()) { range = new LedgerRange(ledgerIds); } // else, hasNext() should return false so that advance will skip us and move on } @Override public boolean hasNext() throws IOException { return range != null; } @Override public LedgerRange next() throws IOException { if (range == null) { throw new NoSuchElementException( "next() must only be called if hasNext() is true"); } LedgerRange ret = range; range = null; return ret; } } /** * The main constraint is that between calls one of two things must be true. * 1) nextLevelIterator is null and thisLevelIterator.hasNext() == false: iteration complete, hasNext() * returns false * 2) nextLevelIterator is non-null: nextLevelIterator.hasNext() must return true and nextLevelIterator.next() * must return the next LedgerRange * The above means that nextLevelIterator != null ==> nextLevelIterator.hasNext() * It also means that hasNext() iff nextLevelIterator != null */ private class InnerIterator implements LedgerRangeIterator { final String path; final int level; // Always non-null final Iterator<String> thisLevelIterator; // non-null iff nextLevelIterator.hasNext() is true LedgerRangeIterator nextLevelIterator; /** * Builds InnerIterator. * * @param path Subpath for thisLevelIterator * @param level Level of thisLevelIterator (must be <= 3) * @throws IOException */ InnerIterator(String path, int level) throws IOException { this.path = path; this.level = level; thisLevelIterator = getChildrenAt(path).iterator(); advance(); } /** * Resolves the difference between cases 1 and 2 after nextLevelIterator is exhausted. * Pre-condition: nextLevelIterator == null, thisLevelIterator != null * Post-condition: nextLevelIterator == null && !thisLevelIterator.hasNext() OR * nextLevelIterator.hasNext() == true and nextLevelIterator.next() * yields the next result of next() * @throws IOException Exception representing error */ void advance() throws IOException { while (thisLevelIterator.hasNext()) { String node = thisLevelIterator.next(); if (level == 0 && !isLedgerParentNode(node)) { continue; } LedgerRangeIterator nextIterator = level < 3 ? new InnerIterator(path + "/" + node, level + 1) : new LeafIterator(path + "/" + node); if (nextIterator.hasNext()) { nextLevelIterator = nextIterator; break; } } } @Override public boolean hasNext() throws IOException { return nextLevelIterator != null; } @Override public LedgerRange next() throws IOException { LedgerRange ret = nextLevelIterator.next(); if (!nextLevelIterator.hasNext()) { nextLevelIterator = null; advance(); } return ret; } } private LongHierarchicalLedgerRangeIterator(long zkOpTimeoutMs) { this.zkOpTimeoutMs = zkOpTimeoutMs; } private void bootstrap() throws IOException { if (rootIterator == null) { rootIterator = new InnerIterator(ledgerRootPath, 0); } } @Override public synchronized boolean hasNext() throws IOException { bootstrap(); return rootIterator.hasNext(); } @Override public synchronized LedgerRange next() throws IOException { bootstrap(); return rootIterator.next(); } } @Override protected String getLedgerParentNodeRegex() { return StringUtils.LONGHIERARCHICAL_LEDGER_PARENT_NODE_REGEX; } }
201
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/MetadataClientDriver.java
/* * 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.bookkeeper.meta; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import org.apache.bookkeeper.common.annotation.InterfaceAudience.LimitedPrivate; import org.apache.bookkeeper.common.annotation.InterfaceStability.Evolving; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.discover.RegistrationClient; import org.apache.bookkeeper.meta.exceptions.MetadataException; import org.apache.bookkeeper.stats.StatsLogger; /** * Driver to manage all the metadata managers required by a bookkeeper client. */ @LimitedPrivate @Evolving public interface MetadataClientDriver extends AutoCloseable { /** * Initialize the metadata driver. * * @param conf configuration * @param scheduler scheduler * @param statsLogger stats logger * @param ctx optional context object passed in for initialization. * currently it is an external zookeeper instance, which can * be used for zookeeper based metadata implementation. * @return metadata driver * @throws MetadataException when fail to initialize the client driver. */ MetadataClientDriver initialize(ClientConfiguration conf, ScheduledExecutorService scheduler, StatsLogger statsLogger, Optional<Object> ctx) throws MetadataException; /** * Get the scheme of the metadata driver. * * @return the scheme of the metadata driver. */ String getScheme(); /** * Return the registration client used for discovering registered bookies. * * @return the registration client used for discovering registered bookies. */ RegistrationClient getRegistrationClient(); /** * Return the ledger manager factory used for accessing ledger metadata. * * @return the ledger manager factory used for accessing ledger metadata. */ LedgerManagerFactory getLedgerManagerFactory() throws MetadataException; /** * Return the layout manager. * * @return the layout manager. */ LayoutManager getLayoutManager(); @Override void close(); /** * State Listener on listening the metadata client session states. */ @FunctionalInterface interface SessionStateListener { /** * Signal when client session is expired. */ void onSessionExpired(); } /** * sets session state listener. * * @param sessionStateListener * listener listening on metadata client session states. */ void setSessionStateListener(SessionStateListener sessionStateListener); /** * Return health check is enable or disable. * * @return true if health check is enable, otherwise false. */ default CompletableFuture<Boolean> isHealthCheckEnabled() { return FutureUtils.value(true); } }
202
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/LedgerManagerFactory.java
/* * 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.bookkeeper.meta; import java.io.IOException; import org.apache.bookkeeper.conf.AbstractConfiguration; import org.apache.bookkeeper.replication.ReplicationException; import org.apache.zookeeper.KeeperException; /** * A factory for creating ledger managers. */ public interface LedgerManagerFactory extends AutoCloseable { /** * Return current factory version. * * @return current version used by factory. */ int getCurrentVersion(); /** * Initialize a factory. * * @param conf * Configuration object used to initialize factory * @param layoutManager * Layout manager used for initialize ledger manager factory * @param factoryVersion * What version used to initialize factory. * @return ledger manager factory instance * @throws IOException when fail to initialize the factory. */ LedgerManagerFactory initialize(AbstractConfiguration conf, LayoutManager layoutManager, int factoryVersion) throws IOException; /** * Uninitialize the factory. * * @throws IOException when fail to uninitialize the factory. */ @Override void close() throws IOException; /** * Return the ledger id generator, which is used for global unique ledger id * generation. * * @return ledger id generator. */ LedgerIdGenerator newLedgerIdGenerator(); /** * return ledger manager for client-side to manage ledger metadata. * * @return ledger manager * @see LedgerManager */ LedgerManager newLedgerManager(); /** * Return a ledger underreplication manager, which is used to * mark ledgers as unreplicated, and to retrieve a ledger which * is underreplicated so that it can be rereplicated. * * @return ledger underreplication manager * @see LedgerUnderreplicationManager */ LedgerUnderreplicationManager newLedgerUnderreplicationManager() throws ReplicationException.UnavailableException, InterruptedException, ReplicationException.CompatibilityException; /** * Return a ledger auditor manager, which is used to * coordinate the auto-recovery process. * * @return ledger auditor manager * @see LedgerAuditorManager */ LedgerAuditorManager newLedgerAuditorManager() throws IOException, InterruptedException; /** * Format the ledger metadata for LedgerManager. * * @param conf * Configuration instance * @param lm * Layout manager */ void format(AbstractConfiguration<?> conf, LayoutManager lm) throws InterruptedException, KeeperException, IOException; /** * This method makes sure there are no unexpected znodes under ledgersRootPath * and then it proceeds with ledger metadata formatting and nuking the cluster * ZK state info. * * @param conf * Configuration instance * @param lm * Layout manager * @throws IOException * @throws KeeperException * @throws InterruptedException */ boolean validateAndNukeExistingCluster(AbstractConfiguration<?> conf, LayoutManager lm) throws InterruptedException, KeeperException, IOException; }
203
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/package-info.java
/* * 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. */ /** * Classes for interacting with bookkeeper ledgers and ledger metadata. */ package org.apache.bookkeeper.meta;
204
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/zk/ZKMetadataBookieDriver.java
/* * 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.bookkeeper.meta.zk; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.BOOKIE_SCOPE; import java.util.Optional; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.discover.ZKRegistrationManager; import org.apache.bookkeeper.meta.MetadataBookieDriver; import org.apache.bookkeeper.meta.MetadataDrivers; import org.apache.bookkeeper.meta.exceptions.MetadataException; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.zookeeper.BoundExponentialBackoffRetryPolicy; /** * ZooKeeper based metadata bookie driver. */ @Slf4j public class ZKMetadataBookieDriver extends ZKMetadataDriverBase implements MetadataBookieDriver { // register myself static { MetadataDrivers.registerBookieDriver( SCHEME, ZKMetadataBookieDriver.class); } ServerConfiguration serverConf; @Override public synchronized MetadataBookieDriver initialize(ServerConfiguration conf, StatsLogger statsLogger) throws MetadataException { super.initialize( conf, statsLogger.scope(BOOKIE_SCOPE), new BoundExponentialBackoffRetryPolicy(conf.getZkRetryBackoffStartMs(), conf.getZkRetryBackoffMaxMs(), conf.getZkRetryBackoffMaxRetries()), Optional.empty()); this.serverConf = conf; this.statsLogger = statsLogger; return this; } @Override public synchronized RegistrationManager createRegistrationManager() { return new ZKRegistrationManager(serverConf, zk); } @Override public void close() { super.close(); } }
205
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/zk/ZKMetadataClientDriver.java
/* * 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.bookkeeper.meta.zk; import java.util.Optional; import java.util.concurrent.ScheduledExecutorService; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.discover.RegistrationClient; import org.apache.bookkeeper.discover.ZKRegistrationClient; import org.apache.bookkeeper.meta.MetadataClientDriver; import org.apache.bookkeeper.meta.MetadataDrivers; import org.apache.bookkeeper.meta.exceptions.MetadataException; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.zookeeper.BoundExponentialBackoffRetryPolicy; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; /** * ZooKeeper based metadata client driver. */ @Slf4j public class ZKMetadataClientDriver extends ZKMetadataDriverBase implements MetadataClientDriver { // register myself to driver manager static { MetadataDrivers.registerClientDriver( SCHEME, ZKMetadataClientDriver.class); } ClientConfiguration clientConf; ScheduledExecutorService scheduler; RegistrationClient regClient; boolean bookieAddressTracking = true; @Override public synchronized MetadataClientDriver initialize(ClientConfiguration conf, ScheduledExecutorService scheduler, StatsLogger statsLogger, Optional<Object> optionalCtx) throws MetadataException { super.initialize( conf, statsLogger, new BoundExponentialBackoffRetryPolicy( conf.getZkTimeout(), conf.getZkTimeout(), conf.getZkRetryBackoffMaxRetries()), optionalCtx); this.statsLogger = statsLogger; this.clientConf = conf; this.scheduler = scheduler; this.bookieAddressTracking = conf.getEnableBookieAddressTracking(); return this; } @Override public synchronized RegistrationClient getRegistrationClient() { if (null == regClient) { regClient = new ZKRegistrationClient( zk, ledgersRootPath, scheduler, bookieAddressTracking); } return regClient; } @Override public synchronized void close() { if (null != regClient) { regClient.close(); regClient = null; } super.close(); } @Override public void setSessionStateListener(SessionStateListener sessionStateListener) { zk.register((event) -> { // Check for expired connection. if (event.getType().equals(EventType.None) && event.getState().equals(KeeperState.Expired)) { sessionStateListener.onSessionExpired(); } }); } }
206
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/zk/package-info.java
/* * 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. */ /** * ZooKeeper based metadata implementation. */ package org.apache.bookkeeper.meta.zk;
207
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/zk/ZKMetadataDriverBase.java
/* * 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.bookkeeper.meta.zk; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.bookkeeper.util.BookKeeperConstants.AVAILABLE_NODE; import static org.apache.bookkeeper.util.BookKeeperConstants.DISABLE_HEALTH_CHECK; import static org.apache.bookkeeper.util.BookKeeperConstants.EMPTY_BYTE_ARRAY; import static org.apache.bookkeeper.util.BookKeeperConstants.READONLY; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import lombok.Getter; import lombok.Setter; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.conf.AbstractConfiguration; import org.apache.bookkeeper.meta.AbstractZkLedgerManagerFactory; import org.apache.bookkeeper.meta.HierarchicalLedgerManagerFactory; import org.apache.bookkeeper.meta.LayoutManager; import org.apache.bookkeeper.meta.LedgerManagerFactory; import org.apache.bookkeeper.meta.LongHierarchicalLedgerManagerFactory; import org.apache.bookkeeper.meta.ZkLayoutManager; import org.apache.bookkeeper.meta.exceptions.Code; import org.apache.bookkeeper.meta.exceptions.MetadataException; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.util.BookKeeperConstants; import org.apache.bookkeeper.util.ZkUtils; import org.apache.bookkeeper.zookeeper.RetryPolicy; import org.apache.bookkeeper.zookeeper.ZooKeeperClient; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.lang3.StringUtils; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; /** * This is a mixin class for supporting zookeeper based metadata driver. */ @Slf4j public class ZKMetadataDriverBase implements AutoCloseable { protected static final String SCHEME = "zk"; public static String getZKServersFromServiceUri(URI uri) { String authority = uri.getAuthority(); if (authority == null) { throw new IllegalArgumentException("Invalid metadata service URI format: " + uri); } return authority.replace(";", ","); } @SuppressWarnings("deprecation") public static String resolveZkServers(AbstractConfiguration<?> conf) { String metadataServiceUriStr = conf.getMetadataServiceUriUnchecked(); if (null == metadataServiceUriStr) { return conf.getZkServers(); } URI metadataServiceUri = URI.create(metadataServiceUriStr); return getZKServersFromServiceUri(metadataServiceUri); } @SuppressWarnings("deprecation") public static String resolveZkLedgersRootPath(AbstractConfiguration<?> conf) { String metadataServiceUriStr = conf.getMetadataServiceUriUnchecked(); if (null == metadataServiceUriStr) { return conf.getZkLedgersRootPath(); } URI metadataServiceUri = URI.create(metadataServiceUriStr); return metadataServiceUri.getPath(); } @SuppressWarnings("deprecation") public static Class<? extends LedgerManagerFactory> resolveLedgerManagerFactory(URI metadataServiceUri) { checkNotNull(metadataServiceUri, "Metadata service uri is null"); String scheme = metadataServiceUri.getScheme(); checkNotNull(scheme, "Invalid metadata service : " + metadataServiceUri); String[] schemeParts = StringUtils.split(scheme.toLowerCase(), '+'); checkArgument(SCHEME.equals(schemeParts[0]), "Unknown metadata service scheme found : " + schemeParts[0]); Class<? extends LedgerManagerFactory> ledgerManagerFactoryClass; if (schemeParts.length > 1) { switch (schemeParts[1]) { case org.apache.bookkeeper.meta.FlatLedgerManagerFactory.NAME: ledgerManagerFactoryClass = org.apache.bookkeeper.meta.FlatLedgerManagerFactory.class; break; case HierarchicalLedgerManagerFactory.NAME: ledgerManagerFactoryClass = HierarchicalLedgerManagerFactory.class; break; case LongHierarchicalLedgerManagerFactory.NAME: ledgerManagerFactoryClass = LongHierarchicalLedgerManagerFactory.class; break; case org.apache.bookkeeper.meta.MSLedgerManagerFactory.NAME: ledgerManagerFactoryClass = org.apache.bookkeeper.meta.MSLedgerManagerFactory.class; break; case "null": // the ledger manager factory class is not set, so the client will be using the class that is // recorded in ledger manager layout. ledgerManagerFactoryClass = null; break; default: throw new IllegalArgumentException("Unknown ledger manager type found '" + schemeParts[1] + "' at uri : " + metadataServiceUri); } } else { // behave as in the +null case, infer the layout from the store or fall back to the default ledgerManagerFactoryClass = null; } return ledgerManagerFactoryClass; } // URI protected AbstractConfiguration<?> conf; protected StatsLogger statsLogger; // zookeeper related variables protected List<ACL> acls; @Getter @Setter protected ZooKeeper zk = null; // whether the zk handle is one we created, or is owned by whoever // instantiated us protected boolean ownZKHandle = false; // disable health check path String disableHealthCheckPath; // ledgers root path protected String ledgersRootPath; // managers protected LayoutManager layoutManager; protected LedgerManagerFactory lmFactory; public String getScheme() { return SCHEME; } @SuppressWarnings("deprecation") @SneakyThrows(InterruptedException.class) protected void initialize(AbstractConfiguration<?> conf, StatsLogger statsLogger, RetryPolicy zkRetryPolicy, Optional<Object> optionalCtx) throws MetadataException { this.conf = conf; this.acls = ZkUtils.getACLs(conf); if (optionalCtx.isPresent() && optionalCtx.get() instanceof ZooKeeper) { this.ledgersRootPath = conf.getZkLedgersRootPath(); log.info("Initialize zookeeper metadata driver with external zookeeper client : ledgersRootPath = {}.", ledgersRootPath); // if an external zookeeper is added, use the zookeeper instance this.zk = (ZooKeeper) (optionalCtx.get()); this.ownZKHandle = false; } else { final String metadataServiceUriStr; try { metadataServiceUriStr = conf.getMetadataServiceUri(); } catch (ConfigurationException e) { log.error("Failed to retrieve metadata service uri from configuration", e); throw new MetadataException( Code.INVALID_METADATA_SERVICE_URI, e); } URI metadataServiceUri = URI.create(metadataServiceUriStr); // get the initialize root path this.ledgersRootPath = metadataServiceUri.getPath(); final String bookieRegistrationPath = ledgersRootPath + "/" + AVAILABLE_NODE; final String bookieReadonlyRegistrationPath = bookieRegistrationPath + "/" + READONLY; // construct the zookeeper final String zkServers; try { zkServers = getZKServersFromServiceUri(metadataServiceUri); } catch (IllegalArgumentException ex) { throw new MetadataException( Code.INVALID_METADATA_SERVICE_URI, ex); } log.info("Initialize zookeeper metadata driver at metadata service uri {} :" + " zkServers = {}, ledgersRootPath = {}.", metadataServiceUriStr, zkServers, ledgersRootPath); try { this.zk = ZooKeeperClient.newBuilder() .connectString(zkServers) .sessionTimeoutMs(conf.getZkTimeout()) .operationRetryPolicy(zkRetryPolicy) .requestRateLimit(conf.getZkRequestRateLimit()) .statsLogger(statsLogger) .build(); if (null == zk.exists(bookieReadonlyRegistrationPath, false)) { try { zk.create(bookieReadonlyRegistrationPath, EMPTY_BYTE_ARRAY, acls, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException e) { // this node is just now created by someone. } catch (KeeperException.NoNodeException e) { // the cluster hasn't been initialized } } } catch (IOException | KeeperException e) { log.error("Failed to create zookeeper client to {}", zkServers, e); MetadataException me = new MetadataException( Code.METADATA_SERVICE_ERROR, "Failed to create zookeeper client to " + zkServers, e); me.fillInStackTrace(); throw me; } this.ownZKHandle = true; } disableHealthCheckPath = ledgersRootPath + "/" + DISABLE_HEALTH_CHECK; // once created the zookeeper client, create the layout manager and registration client this.layoutManager = new ZkLayoutManager( zk, ledgersRootPath, acls); } public LayoutManager getLayoutManager() { return layoutManager; } @SneakyThrows public synchronized LedgerManagerFactory getLedgerManagerFactory() throws MetadataException { if (null == lmFactory) { try { lmFactory = AbstractZkLedgerManagerFactory.newLedgerManagerFactory( conf, layoutManager); } catch (IOException e) { throw new MetadataException( Code.METADATA_SERVICE_ERROR, "Failed to initialized ledger manager factory", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw e; } } return lmFactory; } public CompletableFuture<Void> disableHealthCheck() { CompletableFuture<Void> createResult = new CompletableFuture<>(); zk.create(disableHealthCheckPath, BookKeeperConstants.EMPTY_BYTE_ARRAY, acls, CreateMode.PERSISTENT, new AsyncCallback.StringCallback() { @Override public void processResult(int rc, String path, Object ctx, String name) { if (KeeperException.Code.OK.intValue() == rc) { createResult.complete(null); } else if (KeeperException.Code.NODEEXISTS.intValue() == rc) { if (log.isDebugEnabled()) { log.debug("health check already disabled!"); } createResult.complete(null); } else { createResult.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc), path)); } } }, null); return createResult; } public CompletableFuture<Void> enableHealthCheck() { CompletableFuture<Void> deleteResult = new CompletableFuture<>(); zk.delete(disableHealthCheckPath, -1, new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { if (KeeperException.Code.OK.intValue() == rc) { deleteResult.complete(null); } else if (KeeperException.Code.NONODE.intValue() == rc) { if (log.isDebugEnabled()) { log.debug("health check already enabled!"); } deleteResult.complete(null); } else { deleteResult.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc), path)); } } }, null); return deleteResult; } public CompletableFuture<Boolean> isHealthCheckEnabled() { CompletableFuture<Boolean> enableResult = new CompletableFuture<>(); zk.exists(disableHealthCheckPath, false, new AsyncCallback.StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { if (KeeperException.Code.OK.intValue() == rc) { enableResult.complete(false); } else { enableResult.complete(true); } } }, null); return enableResult; } @Override public void close() { if (null != lmFactory) { try { lmFactory.close(); } catch (IOException e) { log.warn("Failed to close zookeeper based ledger manager", e); } lmFactory = null; } if (ownZKHandle && null != zk) { try { zk.close(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Interrupted on closing zookeeper client", e); } zk = null; } } }
208
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/exceptions/MetadataException.java
/* * 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.bookkeeper.meta.exceptions; import lombok.Getter; /** * Metadata Exception. */ @Getter public class MetadataException extends Exception { private static final long serialVersionUID = -7833758146152388503L; private final Code code; public MetadataException(Code code, String message) { super(message); this.code = code; } public MetadataException(Code code, String message, Throwable cause) { super(message, cause); this.code = code; } public MetadataException(Code code, Throwable cause) { super(cause); this.code = code; } }
209
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/exceptions/Code.java
/* * 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.bookkeeper.meta.exceptions; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Metadata Exception Code. */ @RequiredArgsConstructor @Getter public enum Code { // the passed in metadata service uri is invalid INVALID_METADATA_SERVICE_URI(-1), // encountered service error when talking to the metadata service METADATA_SERVICE_ERROR(-2); private final int code; }
210
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/exceptions/package-info.java
/* * 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. */ /** * Exceptions for metadata service. */ package org.apache.bookkeeper.meta.exceptions;
211
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/Main.java
/* * 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.bookkeeper.server; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.ExitCode; import org.apache.bookkeeper.common.component.ComponentStarter; import org.apache.bookkeeper.common.component.LifecycleComponent; import org.apache.bookkeeper.common.component.LifecycleComponentStack; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.conf.UncheckedConfigurationException; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.configuration.ConfigurationException; /** * A bookie server is a server that run bookie and serving rpc requests. * * <p>It is a rewritten server using {@link org.apache.bookkeeper.common.component.LifecycleComponent}, * replacing the legacy server {@link org.apache.bookkeeper.proto.BookieServer}. */ @Slf4j public class Main { static final Options BK_OPTS = new Options(); static { BK_OPTS.addOption("c", "conf", true, "Configuration for Bookie Server"); BK_OPTS.addOption("withAutoRecovery", false, "Start Autorecovery service Bookie server"); BK_OPTS.addOption("r", "readOnly", false, "Force Start a ReadOnly Bookie server"); BK_OPTS.addOption("z", "zkserver", true, "Zookeeper Server"); BK_OPTS.addOption("m", "zkledgerpath", true, "Zookeeper ledgers root path"); BK_OPTS.addOption("p", "bookieport", true, "bookie port exported"); BK_OPTS.addOption("hp", "httpport", true, "bookie http port exported"); BK_OPTS.addOption("j", "journal", true, "bookie journal directory"); Option indexDirs = new Option ("i", "indexdirs", true, "bookie index directories"); indexDirs.setArgs(10); BK_OPTS.addOption(indexDirs); Option ledgerDirs = new Option ("l", "ledgerdirs", true, "bookie ledgers directories"); ledgerDirs.setArgs(10); BK_OPTS.addOption(ledgerDirs); BK_OPTS.addOption("h", "help", false, "Print help message"); } /** * Print usage. */ private static void printUsage() { HelpFormatter hf = new HelpFormatter(); String header = "\n" + "BookieServer provide an interface to start a bookie with configuration file and/or arguments." + "The settings in configuration file will be overwrite by provided arguments.\n" + "Options including:\n"; String footer = "Here is an example:\n" + "\tBookieServer -c bookie.conf -z localhost:2181 -m /bookkeeper/ledgers " + "-p 3181 -j /mnt/journal -i \"/mnt/index1 /mnt/index2\"" + " -l \"/mnt/ledger1 /mnt/ledger2 /mnt/ledger3\"\n"; hf.printHelp("BookieServer [options]\n", header, BK_OPTS, footer, true); } private static void loadConfFile(ServerConfiguration conf, String confFile) throws IllegalArgumentException { try { conf.loadConf(new File(confFile).toURI().toURL()); conf.validate(); } catch (MalformedURLException e) { log.error("Could not open configuration file: {}", confFile, e); throw new IllegalArgumentException(); } catch (ConfigurationException e) { log.error("Malformed configuration file: {}", confFile, e); throw new IllegalArgumentException(); } log.info("Using configuration file {}", confFile); } @SuppressWarnings("deprecation") private static ServerConfiguration parseArgs(String[] args) throws IllegalArgumentException { try { BasicParser parser = new BasicParser(); CommandLine cmdLine = parser.parse(BK_OPTS, args); if (cmdLine.hasOption('h')) { throw new IllegalArgumentException(); } ServerConfiguration conf = new ServerConfiguration(); if (cmdLine.hasOption('c')) { String confFile = cmdLine.getOptionValue("c"); loadConfFile(conf, confFile); } if (cmdLine.hasOption("withAutoRecovery")) { conf.setAutoRecoveryDaemonEnabled(true); } if (cmdLine.hasOption("r")) { conf.setForceReadOnlyBookie(true); } boolean overwriteMetadataServiceUri = false; String sZkLedgersRootPath = "/ledgers"; if (cmdLine.hasOption('m')) { sZkLedgersRootPath = cmdLine.getOptionValue('m'); log.info("Get cmdline zookeeper ledger path: {}", sZkLedgersRootPath); overwriteMetadataServiceUri = true; } String sZK = conf.getZkServers(); if (cmdLine.hasOption('z')) { sZK = cmdLine.getOptionValue('z'); log.info("Get cmdline zookeeper instance: {}", sZK); overwriteMetadataServiceUri = true; } // command line arguments overwrite settings in configuration file if (overwriteMetadataServiceUri) { String metadataServiceUri = "zk://" + sZK + sZkLedgersRootPath; conf.setMetadataServiceUri(metadataServiceUri); log.info("Overwritten service uri to {}", metadataServiceUri); } if (cmdLine.hasOption('p')) { String sPort = cmdLine.getOptionValue('p'); log.info("Get cmdline bookie port: {}", sPort); conf.setBookiePort(Integer.parseInt(sPort)); } if (cmdLine.hasOption("httpport")) { String sPort = cmdLine.getOptionValue("httpport"); log.info("Get cmdline http port: {}", sPort); Integer iPort = Integer.parseInt(sPort); conf.setHttpServerPort(iPort.intValue()); } if (cmdLine.hasOption('j')) { String sJournalDir = cmdLine.getOptionValue('j'); log.info("Get cmdline journal dir: {}", sJournalDir); conf.setJournalDirName(sJournalDir); } if (cmdLine.hasOption('i')) { String[] sIndexDirs = cmdLine.getOptionValues('i'); log.info("Get cmdline index dirs: "); for (String index : sIndexDirs) { log.info("indexDir : {}", index); } conf.setIndexDirName(sIndexDirs); } if (cmdLine.hasOption('l')) { String[] sLedgerDirs = cmdLine.getOptionValues('l'); log.info("Get cmdline ledger dirs: "); for (String ledger : sLedgerDirs) { log.info("ledgerdir : {}", ledger); } conf.setLedgerDirNames(sLedgerDirs); } return conf; } catch (ParseException e) { log.error("Error parsing command line arguments : ", e); throw new IllegalArgumentException(e); } } public static void main(String[] args) { int retCode = doMain(args); Runtime.getRuntime().exit(retCode); } static int doMain(String[] args) { ServerConfiguration conf; // 0. parse command line try { conf = parseCommandLine(args); } catch (IllegalArgumentException iae) { return ExitCode.INVALID_CONF; } // 1. building the component stack: LifecycleComponent server; try { server = buildBookieServer(new BookieConfiguration(conf)); } catch (Exception e) { log.error("Failed to build bookie server", e); return ExitCode.SERVER_EXCEPTION; } // 2. start the server try { ComponentStarter.startComponent(server).get(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); // the server is interrupted log.info("Bookie server is interrupted. Exiting ..."); } catch (ExecutionException ee) { log.error("Error in bookie shutdown", ee.getCause()); return ExitCode.SERVER_EXCEPTION; } return ExitCode.OK; } private static ServerConfiguration parseCommandLine(String[] args) throws IllegalArgumentException, UncheckedConfigurationException { ServerConfiguration conf; try { conf = parseArgs(args); } catch (IllegalArgumentException iae) { log.error("Error parsing command line arguments : ", iae); System.err.println(iae.getMessage()); printUsage(); throw iae; } String hello = String.format( "Hello, I'm your bookie, bookieId is %1$s, listening on port %2$s. Metadata service uri is %3$s." + " Journals are in %4$s. Ledgers are stored in %5$s. Indexes are stored in %6$s.", conf.getBookieId() != null ? conf.getBookieId() : "<not-set>", conf.getBookiePort(), conf.getMetadataServiceUriUnchecked(), Arrays.asList(conf.getJournalDirNames()), Arrays.asList(conf.getLedgerDirNames()), Arrays.asList(conf.getIndexDirNames() != null ? conf.getIndexDirNames() : conf.getLedgerDirNames())); log.info(hello); return conf; } /** * Build the bookie server. * * <p>The sequence of the components is: * * <pre> * - stats provider * - bookie server * - autorecovery daemon * - http service * </pre> * * @param conf bookie server configuration * @return lifecycle stack */ public static LifecycleComponentStack buildBookieServer(BookieConfiguration conf) throws Exception { return EmbeddedServer.builder(conf).build().getLifecycleComponentStack(); } public static List<File> storageDirectoriesFromConf(ServerConfiguration conf) throws IOException { List<File> dirs = new ArrayList<>(); File[] journalDirs = conf.getJournalDirs(); if (journalDirs != null) { for (File j : journalDirs) { File cur = BookieImpl.getCurrentDirectory(j); if (!dirs.stream().anyMatch(f -> f.equals(cur))) { BookieImpl.checkDirectoryStructure(cur); dirs.add(cur); } } } File[] ledgerDirs = conf.getLedgerDirs(); if (ledgerDirs != null) { for (File l : ledgerDirs) { File cur = BookieImpl.getCurrentDirectory(l); if (!dirs.stream().anyMatch(f -> f.equals(cur))) { BookieImpl.checkDirectoryStructure(cur); dirs.add(cur); } } } File[] indexDirs = conf.getIndexDirs(); if (indexDirs != null) { for (File i : indexDirs) { File cur = BookieImpl.getCurrentDirectory(i); if (!dirs.stream().anyMatch(f -> f.equals(cur))) { BookieImpl.checkDirectoryStructure(cur); dirs.add(cur); } } } return dirs; } }
212
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/EmbeddedServer.java
/* * * 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.bookkeeper.server; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.BOOKIE_SCOPE; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.LD_INDEX_SCOPE; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.LD_LEDGER_SCOPE; import static org.apache.bookkeeper.client.BookKeeperClientStats.CLIENT_SCOPE; import static org.apache.bookkeeper.replication.ReplicationStats.REPLICATION_SCOPE; import static org.apache.bookkeeper.server.Main.storageDirectoriesFromConf; import static org.apache.bookkeeper.server.component.ServerLifecycleComponent.loadServerComponents; import com.google.common.base.Ticker; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.CompositeByteBuf; import io.reactivex.rxjava3.core.Scheduler; import io.reactivex.rxjava3.schedulers.Schedulers; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.BookieResources; import org.apache.bookkeeper.bookie.CookieValidation; import org.apache.bookkeeper.bookie.LedgerDirsManager; import org.apache.bookkeeper.bookie.LedgerStorage; import org.apache.bookkeeper.bookie.LegacyCookieValidation; import org.apache.bookkeeper.bookie.ReadOnlyBookie; import org.apache.bookkeeper.bookie.ScrubberStats; import org.apache.bookkeeper.bookie.UncleanShutdownDetection; import org.apache.bookkeeper.bookie.UncleanShutdownDetectionImpl; import org.apache.bookkeeper.bookie.datainteg.DataIntegrityCheck; import org.apache.bookkeeper.bookie.datainteg.DataIntegrityCheckImpl; import org.apache.bookkeeper.bookie.datainteg.DataIntegrityCookieValidation; import org.apache.bookkeeper.bookie.datainteg.DataIntegrityService; import org.apache.bookkeeper.bookie.datainteg.EntryCopier; import org.apache.bookkeeper.bookie.datainteg.EntryCopierImpl; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.common.allocator.ByteBufAllocatorWithOomHandler; import org.apache.bookkeeper.common.component.AutoCloseableLifecycleComponent; import org.apache.bookkeeper.common.component.ComponentInfoPublisher; import org.apache.bookkeeper.common.component.LifecycleComponentStack; import org.apache.bookkeeper.common.component.RxSchedulerLifecycleComponent; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.discover.BookieServiceInfo; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerManagerFactory; import org.apache.bookkeeper.meta.MetadataBookieDriver; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.server.component.ServerLifecycleComponent; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.bookkeeper.server.http.BKHttpServiceProvider; import org.apache.bookkeeper.server.service.AutoRecoveryService; import org.apache.bookkeeper.server.service.BookieService; import org.apache.bookkeeper.server.service.HttpService; import org.apache.bookkeeper.server.service.ScrubberService; import org.apache.bookkeeper.server.service.StatsProviderService; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.stats.StatsProvider; import org.apache.bookkeeper.util.DiskChecker; import org.apache.commons.lang3.StringUtils; /** * An embedded server is a server that run bookie and serving rpc requests. * * <p> * It is a rewritten server using {@link org.apache.bookkeeper.common.component.LifecycleComponent}, replacing the * legacy server {@link org.apache.bookkeeper.proto.BookieServer}. */ public class EmbeddedServer { private final LifecycleComponentStack lifecycleComponentStack; private final StatsProvider statsProvider; private final RegistrationManager registrationManager; private final LedgerManagerFactory ledgerManagerFactory; private final DiskChecker diskChecker; private final LedgerDirsManager ledgerDirsManager; private final LedgerDirsManager indexDirsManager; private final BookieService bookieService; private final AutoRecoveryService autoRecoveryService; private final DataIntegrityService dataIntegrityService; private final HttpService httpService; private EmbeddedServer(LifecycleComponentStack lifecycleComponentStack, StatsProvider statsProvider, RegistrationManager registrationManager, LedgerManagerFactory ledgerManagerFactory, DiskChecker diskChecker, LedgerDirsManager ledgerDirsManager, LedgerDirsManager indexDirsManager, BookieService bookieService, AutoRecoveryService autoRecoveryService, DataIntegrityService dataIntegrityService, HttpService httpService) { this.lifecycleComponentStack = lifecycleComponentStack; this.statsProvider = statsProvider; this.registrationManager = registrationManager; this.ledgerManagerFactory = ledgerManagerFactory; this.diskChecker = diskChecker; this.ledgerDirsManager = ledgerDirsManager; this.indexDirsManager = indexDirsManager; this.bookieService = bookieService; this.autoRecoveryService = autoRecoveryService; this.dataIntegrityService = dataIntegrityService; this.httpService = httpService; } public LifecycleComponentStack getLifecycleComponentStack() { return lifecycleComponentStack; } public StatsProvider getStatsProvider() { return statsProvider; } public RegistrationManager getRegistrationManager() { return registrationManager; } public LedgerManagerFactory getLedgerManagerFactory() { return ledgerManagerFactory; } public DiskChecker getDiskChecker() { return diskChecker; } public LedgerDirsManager getLedgerDirsManager() { return ledgerDirsManager; } public LedgerDirsManager getIndexDirsManager() { return indexDirsManager; } public BookieService getBookieService() { return bookieService; } public AutoRecoveryService getAutoRecoveryService() { return autoRecoveryService; } public DataIntegrityService getDataIntegrityService() { return dataIntegrityService; } public HttpService getHttpService() { return httpService; } /** * Create a new builder from given configuration. Actual services implementations can be provided to the builder and * will override ones defined in the configuration. * <p> * Invoker is responsible to start and stop provided services implementations, components from * {@link EmbeddedServer#getLifecycleComponentStack()} will reflect only those created from provided configuration. * * @param conf bookie configuration * @return a new embedded server builder */ public static final Builder builder(BookieConfiguration conf) { return new Builder(conf); } @Slf4j public static class Builder { private BookieConfiguration conf; private StatsProvider statsProvider; private MetadataBookieDriver metadataDriver; private RegistrationManager registrationManager; private LedgerManagerFactory ledgerManagerFactory; private DiskChecker diskChecker; private LedgerDirsManager ledgerDirsManager; private LedgerDirsManager indexDirsManager; private ByteBufAllocator allocator; private UncleanShutdownDetection uncleanShutdownDetection; private Builder(BookieConfiguration conf) { checkNotNull(conf, "bookieConfiguration cannot be null"); this.conf = conf; } public Builder statsProvider(StatsProvider statsProvider) { this.statsProvider = statsProvider; return this; } public Builder metadataDriver(MetadataBookieDriver metadataDriver) { this.metadataDriver = metadataDriver; return this; } public Builder registrationManager(RegistrationManager registrationManager) { this.registrationManager = registrationManager; return this; } public Builder ledgerManagerFactory(LedgerManagerFactory ledgerManagerFactory) { this.ledgerManagerFactory = ledgerManagerFactory; return this; } public Builder diskChecker(DiskChecker diskChecker) { this.diskChecker = diskChecker; return this; } public Builder ledgerDirsManager(LedgerDirsManager ledgerDirsManager) { this.ledgerDirsManager = ledgerDirsManager; return this; } public Builder indexDirsManager(LedgerDirsManager indexDirsManager) { this.indexDirsManager = indexDirsManager; return this; } public Builder allocator(ByteBufAllocator allocator) { this.allocator = allocator; return this; } public Builder uncleanShutdownDetection(UncleanShutdownDetection uncleanShutdownDetection) { this.uncleanShutdownDetection = uncleanShutdownDetection; return this; } /** * Build the bookie server. * * <p> * The sequence of the components is: * * <pre> * - stats provider * - bookie server * - autorecovery daemon * - http service * </pre> * * @return lifecycle stack * @throws java.lang.Exception */ public EmbeddedServer build() throws Exception { final ComponentInfoPublisher componentInfoPublisher = new ComponentInfoPublisher(); final Supplier<BookieServiceInfo> bookieServiceInfoProvider = () -> buildBookieServiceInfo(componentInfoPublisher); LifecycleComponentStack.Builder serverBuilder = LifecycleComponentStack .newBuilder() .withComponentInfoPublisher(componentInfoPublisher) .withName("bookie-server"); // 1. build stats provider if (statsProvider == null) { StatsProviderService statsProviderService = new StatsProviderService(conf); statsProvider = statsProviderService.getStatsProvider(); serverBuilder.addComponent(statsProviderService); log.info("Load lifecycle component : {}", statsProviderService.getName()); } StatsLogger rootStatsLogger = statsProvider.getStatsLogger(""); // 2. Build metadata driver if (metadataDriver == null) { if (ledgerManagerFactory == null || registrationManager == null) { metadataDriver = BookieResources.createMetadataDriver(conf.getServerConf(), rootStatsLogger); serverBuilder.addComponent(new AutoCloseableLifecycleComponent("metadataDriver", metadataDriver)); } } if (registrationManager == null) { registrationManager = metadataDriver.createRegistrationManager(); serverBuilder.addComponent( new AutoCloseableLifecycleComponent("registrationManager", registrationManager)); } // 3. Build ledger manager if (ledgerManagerFactory == null) { ledgerManagerFactory = metadataDriver.getLedgerManagerFactory(); serverBuilder.addComponent(new AutoCloseableLifecycleComponent("lmFactory", ledgerManagerFactory)); } LedgerManager ledgerManager = ledgerManagerFactory.newLedgerManager(); serverBuilder.addComponent(new AutoCloseableLifecycleComponent("ledgerManager", ledgerManager)); // 4. Build bookie StatsLogger bookieStats = rootStatsLogger.scope(BOOKIE_SCOPE); if (diskChecker == null) { diskChecker = BookieResources.createDiskChecker(conf.getServerConf()); } if (ledgerDirsManager == null) { ledgerDirsManager = BookieResources.createLedgerDirsManager( conf.getServerConf(), diskChecker, bookieStats.scope(LD_LEDGER_SCOPE)); } if (indexDirsManager == null) { indexDirsManager = BookieResources.createIndexDirsManager( conf.getServerConf(), diskChecker, bookieStats.scope(LD_INDEX_SCOPE), ledgerDirsManager); } ByteBufAllocatorWithOomHandler allocatorWithOomHandler; if (allocator == null) { allocatorWithOomHandler = BookieResources.createAllocator(conf.getServerConf()); allocator = allocatorWithOomHandler; } else { if (allocator instanceof ByteBufAllocatorWithOomHandler) { allocatorWithOomHandler = (ByteBufAllocatorWithOomHandler) allocator; } else { allocatorWithOomHandler = new ByteBuffAllocatorWrapper(allocator); } } if (uncleanShutdownDetection == null) { uncleanShutdownDetection = new UncleanShutdownDetectionImpl(ledgerDirsManager); } if (uncleanShutdownDetection.lastShutdownWasUnclean()) { log.info("Unclean shutdown detected. " + "The bookie did not register a graceful shutdown prior to this boot."); } // bookie takes ownership of storage, so shuts it down LedgerStorage storage = null; DataIntegrityCheck integCheck = null; if (conf.getServerConf().isDataIntegrityCheckingEnabled()) { StatsLogger clientStats = bookieStats.scope(CLIENT_SCOPE); ClientConfiguration clientConfiguration = new ClientConfiguration(conf.getServerConf()); clientConfiguration.setClientRole(ClientConfiguration.CLIENT_ROLE_SYSTEM); BookKeeper bkc = BookKeeper.forConfig(clientConfiguration).statsLogger(clientStats).build(); serverBuilder.addComponent(new AutoCloseableLifecycleComponent("bkc", bkc)); BookieId bookieId = BookieImpl.getBookieId(conf.getServerConf()); ExecutorService rxExecutor = Executors.newFixedThreadPool( 2, new ThreadFactoryBuilder().setNameFormat("rx-schedule-%d") .setUncaughtExceptionHandler( (t, ex) -> log.error("Uncaught exception on thread {}", t.getName(), ex)) .build()); Scheduler rxScheduler = Schedulers.from(rxExecutor); serverBuilder.addComponent( new RxSchedulerLifecycleComponent("rx-scheduler", conf, bookieStats, rxScheduler, rxExecutor)); storage = BookieResources.createLedgerStorage(conf.getServerConf(), ledgerManager, ledgerDirsManager, indexDirsManager, bookieStats, allocator); EntryCopier copier = new EntryCopierImpl(bookieId, ((org.apache.bookkeeper.client.BookKeeper) bkc).getClientCtx().getBookieClient(), storage, Ticker.systemTicker()); integCheck = new DataIntegrityCheckImpl(bookieId, ledgerManager, storage, copier, new BookKeeperAdmin(bkc, clientStats, clientConfiguration), rxScheduler); // if we're running with journal writes disabled and an unclean shutdown occurred then // run the preboot check to protect against data loss and to perform data repair if (!conf.getServerConf().getJournalWriteData() && uncleanShutdownDetection.lastShutdownWasUnclean()) { integCheck.runPreBootCheck("UNCLEAN_SHUTDOWN"); } CookieValidation cookieValidation = new DataIntegrityCookieValidation(conf.getServerConf(), registrationManager, integCheck); cookieValidation.checkCookies(storageDirectoriesFromConf(conf.getServerConf())); } else { CookieValidation cookieValidation = new LegacyCookieValidation(conf.getServerConf(), registrationManager); cookieValidation.checkCookies(storageDirectoriesFromConf(conf.getServerConf())); // storage should be created after legacy validation or it will fail (it would find ledger dirs) storage = BookieResources.createLedgerStorage(conf.getServerConf(), ledgerManager, ledgerDirsManager, indexDirsManager, bookieStats, allocator); } Bookie bookie; if (conf.getServerConf().isForceReadOnlyBookie()) { bookie = new ReadOnlyBookie(conf.getServerConf(), registrationManager, storage, diskChecker, ledgerDirsManager, indexDirsManager, bookieStats, allocator, bookieServiceInfoProvider); } else { bookie = new BookieImpl(conf.getServerConf(), registrationManager, storage, diskChecker, ledgerDirsManager, indexDirsManager, bookieStats, allocator, bookieServiceInfoProvider); } // 5. build bookie server BookieService bookieService = new BookieService(conf, bookie, rootStatsLogger, allocatorWithOomHandler, uncleanShutdownDetection); serverBuilder.addComponent(bookieService); log.info("Load lifecycle component : {}", bookieService.getName()); if (conf.getServerConf().isLocalScrubEnabled()) { serverBuilder.addComponent( new ScrubberService( rootStatsLogger.scope(ScrubberStats.SCOPE), conf, bookieService.getServer().getBookie().getLedgerStorage())); } // 6. build auto recovery AutoRecoveryService autoRecoveryService = null; if (conf.getServerConf().isAutoRecoveryDaemonEnabled()) { autoRecoveryService = new AutoRecoveryService(conf, rootStatsLogger.scope(REPLICATION_SCOPE)); serverBuilder.addComponent(autoRecoveryService); log.info("Load lifecycle component : {}", autoRecoveryService.getName()); } // 7. build data integrity check service DataIntegrityService dataIntegrityService = null; if (conf.getServerConf().isDataIntegrityCheckingEnabled()) { checkNotNull(integCheck, "integCheck should have been initialized with the cookie validation"); dataIntegrityService = new DataIntegrityService(conf, rootStatsLogger.scope(REPLICATION_SCOPE), integCheck); serverBuilder.addComponent(dataIntegrityService); log.info("Load lifecycle component : {}", dataIntegrityService.getName()); } // 8. build http service HttpService httpService = null; if (conf.getServerConf().isHttpServerEnabled()) { BKHttpServiceProvider provider = new BKHttpServiceProvider.Builder() .setBookieServer(bookieService.getServer()) .setServerConfiguration(conf.getServerConf()) .setStatsProvider(statsProvider) .setLedgerManagerFactory(ledgerManagerFactory) .build(); httpService = new HttpService(provider, conf, rootStatsLogger); serverBuilder.addComponent(httpService); log.info("Load lifecycle component : {}", httpService.getName()); } // 9. build extra services String[] extraComponents = conf.getServerConf().getExtraServerComponents(); if (null != extraComponents) { try { List<ServerLifecycleComponent> components = loadServerComponents( extraComponents, conf, rootStatsLogger); for (ServerLifecycleComponent component : components) { serverBuilder.addComponent(component); log.info("Load lifecycle component : {}", component.getName()); } } catch (Exception e) { if (conf.getServerConf().getIgnoreExtraServerComponentsStartupFailures()) { log.info("Failed to load extra components '{}' - {}. Continuing without those components.", StringUtils.join(extraComponents), e.getMessage()); } else { throw e; } } } return new EmbeddedServer(serverBuilder.build(), statsProvider, registrationManager, ledgerManagerFactory, diskChecker, ledgerDirsManager, indexDirsManager, bookieService, autoRecoveryService, dataIntegrityService, httpService); } /** * Create the {@link BookieServiceInfo} starting from the published endpoints. * * @see ComponentInfoPublisher * @param componentInfoPublisher the endpoint publisher * @return the created bookie service info */ private static BookieServiceInfo buildBookieServiceInfo(ComponentInfoPublisher componentInfoPublisher) { List<BookieServiceInfo.Endpoint> endpoints = componentInfoPublisher.getEndpoints().values() .stream().map(e -> { return new BookieServiceInfo.Endpoint( e.getId(), e.getPort(), e.getHost(), e.getProtocol(), e.getAuth(), e.getExtensions() ); }).collect(Collectors.toList()); return new BookieServiceInfo(componentInfoPublisher.getProperties(), endpoints); } } private static final class ByteBuffAllocatorWrapper implements ByteBufAllocatorWithOomHandler { private final ByteBufAllocator allocator; @Override public ByteBuf buffer() { return allocator.buffer(); } @Override public ByteBuf buffer(int i) { return allocator.buffer(i); } @Override public ByteBuf buffer(int i, int i1) { return allocator.buffer(i, i1); } @Override public ByteBuf ioBuffer() { return allocator.ioBuffer(); } @Override public ByteBuf ioBuffer(int i) { return allocator.ioBuffer(i); } @Override public ByteBuf ioBuffer(int i, int i1) { return allocator.ioBuffer(i, i1); } @Override public ByteBuf heapBuffer() { return allocator.heapBuffer(); } @Override public ByteBuf heapBuffer(int i) { return allocator.heapBuffer(i); } @Override public ByteBuf heapBuffer(int i, int i1) { return allocator.heapBuffer(i, i1); } @Override public ByteBuf directBuffer() { return allocator.directBuffer(); } @Override public ByteBuf directBuffer(int i) { return allocator.directBuffer(i); } @Override public ByteBuf directBuffer(int i, int i1) { return allocator.directBuffer(i, i1); } @Override public CompositeByteBuf compositeBuffer() { return allocator.compositeBuffer(); } @Override public CompositeByteBuf compositeBuffer(int i) { return allocator.compositeBuffer(i); } @Override public CompositeByteBuf compositeHeapBuffer() { return allocator.compositeHeapBuffer(); } @Override public CompositeByteBuf compositeHeapBuffer(int i) { return allocator.compositeHeapBuffer(i); } @Override public CompositeByteBuf compositeDirectBuffer() { return allocator.compositeDirectBuffer(); } @Override public CompositeByteBuf compositeDirectBuffer(int i) { return allocator.compositeDirectBuffer(i); } @Override public boolean isDirectBufferPooled() { return allocator.isDirectBufferPooled(); } @Override public int calculateNewCapacity(int i, int i1) { return allocator.calculateNewCapacity(i, i1); } public ByteBuffAllocatorWrapper(ByteBufAllocator allocator) { this.allocator = allocator; } @Override public void setOomHandler(Consumer<OutOfMemoryError> handler) { // NOP } } }
213
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/package-info.java
/* * 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. */ /** * BookKeeper Server (Bookie) related components. * * <p>This is the new relocation for any sever related classes. It is to prepare for separating common, protocol, * client and server modules. */ package org.apache.bookkeeper.server;
214
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/component/ServerLifecycleComponent.java
/* * 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.bookkeeper.server.component; import com.google.common.collect.Lists; import java.lang.reflect.Constructor; import java.util.List; import lombok.experimental.PackagePrivate; import org.apache.bookkeeper.common.annotation.InterfaceStability.Evolving; import org.apache.bookkeeper.common.component.AbstractLifecycleComponent; import org.apache.bookkeeper.common.component.LifecycleComponent; import org.apache.bookkeeper.common.util.ReflectionUtils; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.bookkeeper.stats.StatsLogger; /** * A {@link LifecycleComponent} that runs on a bookie server. It can be loaded via reflections. */ @PackagePrivate @Evolving public abstract class ServerLifecycleComponent extends AbstractLifecycleComponent<BookieConfiguration> { public static List<ServerLifecycleComponent> loadServerComponents(String[] componentClassNames, BookieConfiguration conf, StatsLogger statsLogger) { List<Class<? extends ServerLifecycleComponent>> componentClasses = Lists.newArrayListWithExpectedSize(componentClassNames.length); for (String componentClsName : componentClassNames) { componentClasses.add(ReflectionUtils.forName(componentClsName, ServerLifecycleComponent.class)); } return Lists.transform(componentClasses, cls -> newComponent(cls, conf, statsLogger)); } static ServerLifecycleComponent newComponent(Class<? extends ServerLifecycleComponent> theCls, BookieConfiguration conf, StatsLogger statsLogger) { try { Constructor<? extends ServerLifecycleComponent> constructor = theCls.getConstructor(BookieConfiguration.class, StatsLogger.class); constructor.setAccessible(true); return constructor.newInstance(conf, statsLogger); } catch (Exception e) { throw new RuntimeException(e); } } protected ServerLifecycleComponent(String componentName, BookieConfiguration conf, StatsLogger statsLogger) { super(componentName, conf, statsLogger); } }
215
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/component/package-info.java
/* * 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. */ /** * The lifecycle components that run on a bookie server. */ package org.apache.bookkeeper.server.component;
216
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/BKHttpServiceProvider.java
/* * 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.bookkeeper.server.http; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer.ApiType; import org.apache.bookkeeper.http.HttpServiceProvider; import org.apache.bookkeeper.http.service.ErrorHttpService; import org.apache.bookkeeper.http.service.HeartbeatService; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.meta.LedgerManagerFactory; import org.apache.bookkeeper.proto.BookieServer; import org.apache.bookkeeper.replication.Auditor; import org.apache.bookkeeper.replication.AutoRecoveryMain; import org.apache.bookkeeper.server.http.service.AutoRecoveryStatusService; import org.apache.bookkeeper.server.http.service.BookieInfoService; import org.apache.bookkeeper.server.http.service.BookieIsReadyService; import org.apache.bookkeeper.server.http.service.BookieSanityService; import org.apache.bookkeeper.server.http.service.BookieStateReadOnlyService; import org.apache.bookkeeper.server.http.service.BookieStateService; import org.apache.bookkeeper.server.http.service.ClusterInfoService; import org.apache.bookkeeper.server.http.service.ConfigurationService; import org.apache.bookkeeper.server.http.service.DecommissionService; import org.apache.bookkeeper.server.http.service.DeleteLedgerService; import org.apache.bookkeeper.server.http.service.ExpandStorageService; import org.apache.bookkeeper.server.http.service.GCDetailsService; import org.apache.bookkeeper.server.http.service.GetLastLogMarkService; import org.apache.bookkeeper.server.http.service.GetLedgerMetaService; import org.apache.bookkeeper.server.http.service.ListBookieInfoService; import org.apache.bookkeeper.server.http.service.ListBookiesService; import org.apache.bookkeeper.server.http.service.ListDiskFilesService; import org.apache.bookkeeper.server.http.service.ListLedgerService; import org.apache.bookkeeper.server.http.service.ListUnderReplicatedLedgerService; import org.apache.bookkeeper.server.http.service.LostBookieRecoveryDelayService; import org.apache.bookkeeper.server.http.service.MetricsService; import org.apache.bookkeeper.server.http.service.ReadLedgerEntryService; import org.apache.bookkeeper.server.http.service.RecoveryBookieService; import org.apache.bookkeeper.server.http.service.ResumeCompactionService; import org.apache.bookkeeper.server.http.service.SuspendCompactionService; import org.apache.bookkeeper.server.http.service.TriggerAuditService; import org.apache.bookkeeper.server.http.service.TriggerGCService; import org.apache.bookkeeper.server.http.service.TriggerLocationCompactService; import org.apache.bookkeeper.server.http.service.WhoIsAuditorService; import org.apache.bookkeeper.stats.StatsProvider; import org.apache.zookeeper.KeeperException; /** * Bookkeeper based implementation of HttpServiceProvider, * which provide bookkeeper services to handle http requests * from different http endpoints. */ @Slf4j public class BKHttpServiceProvider implements HttpServiceProvider { private final StatsProvider statsProvider; private final BookieServer bookieServer; private final AutoRecoveryMain autoRecovery; private final LedgerManagerFactory ledgerManagerFactory; private final ServerConfiguration serverConf; private final BookKeeperAdmin bka; private final ExecutorService executor; private BKHttpServiceProvider(BookieServer bookieServer, AutoRecoveryMain autoRecovery, LedgerManagerFactory ledgerManagerFactory, ServerConfiguration serverConf, StatsProvider statsProvider) throws IOException, KeeperException, InterruptedException, BKException { this.bookieServer = bookieServer; this.autoRecovery = autoRecovery; this.ledgerManagerFactory = ledgerManagerFactory; this.serverConf = serverConf; this.statsProvider = statsProvider; ClientConfiguration clientConfiguration = new ClientConfiguration(serverConf); this.bka = new BookKeeperAdmin(clientConfiguration); this.executor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("BKHttpServiceThread").setDaemon(true).build()); } @Override public void close() throws IOException { try { executor.shutdown(); if (bka != null) { bka.close(); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); log.error("Interruption while closing BKHttpServiceProvider", ie); throw new IOException("Interruption while closing BKHttpServiceProvider", ie); } catch (BKException e) { log.error("Error while closing BKHttpServiceProvider", e); throw new IOException("Error while closing BKHttpServiceProvider", e); } } private ServerConfiguration getServerConf() { return serverConf; } private Auditor getAuditor() { return autoRecovery == null ? null : autoRecovery.getAuditor(); } private Bookie getBookie() { return bookieServer == null ? null : bookieServer.getBookie(); } /** * Builder for HttpServiceProvider. */ public static class Builder { BookieServer bookieServer = null; AutoRecoveryMain autoRecovery = null; LedgerManagerFactory ledgerManagerFactory = null; ServerConfiguration serverConf = null; StatsProvider statsProvider = null; public Builder setBookieServer(BookieServer bookieServer) { this.bookieServer = bookieServer; return this; } public Builder setAutoRecovery(AutoRecoveryMain autoRecovery) { this.autoRecovery = autoRecovery; return this; } public Builder setServerConfiguration(ServerConfiguration conf) { this.serverConf = conf; return this; } public Builder setStatsProvider(StatsProvider statsProvider) { this.statsProvider = statsProvider; return this; } public Builder setLedgerManagerFactory(LedgerManagerFactory ledgerManagerFactory) { this.ledgerManagerFactory = ledgerManagerFactory; return this; } public BKHttpServiceProvider build() throws IOException, KeeperException, InterruptedException, BKException { return new BKHttpServiceProvider( bookieServer, autoRecovery, ledgerManagerFactory, serverConf, statsProvider ); } } @Override public HttpEndpointService provideHttpEndpointService(ApiType type) { ServerConfiguration configuration = getServerConf(); if (configuration == null) { return new ErrorHttpService(); } switch (type) { case HEARTBEAT: return new HeartbeatService(); case SERVER_CONFIG: return new ConfigurationService(configuration); case METRICS: return new MetricsService(configuration, statsProvider); // ledger case DELETE_LEDGER: return new DeleteLedgerService(configuration); case LIST_LEDGER: return new ListLedgerService(configuration, ledgerManagerFactory); case GET_LEDGER_META: return new GetLedgerMetaService(configuration, ledgerManagerFactory); case READ_LEDGER_ENTRY: return new ReadLedgerEntryService(configuration, bka); // bookie case LIST_BOOKIES: return new ListBookiesService(configuration, bka); case LIST_BOOKIE_INFO: return new ListBookieInfoService(configuration); case LAST_LOG_MARK: return new GetLastLogMarkService(configuration); case LIST_DISK_FILE: return new ListDiskFilesService(configuration); case EXPAND_STORAGE: return new ExpandStorageService(configuration); case GC: return new TriggerGCService(configuration, bookieServer); case GC_DETAILS: return new GCDetailsService(configuration, bookieServer); case BOOKIE_STATE: return new BookieStateService(bookieServer.getBookie()); case BOOKIE_SANITY: return new BookieSanityService(configuration); case BOOKIE_STATE_READONLY: return new BookieStateReadOnlyService(bookieServer.getBookie()); case BOOKIE_IS_READY: return new BookieIsReadyService(bookieServer.getBookie()); case BOOKIE_INFO: return new BookieInfoService(bookieServer.getBookie()); case CLUSTER_INFO: return new ClusterInfoService(bka, ledgerManagerFactory); case SUSPEND_GC_COMPACTION: return new SuspendCompactionService(bookieServer); case RESUME_GC_COMPACTION: return new ResumeCompactionService(bookieServer); case TRIGGER_ENTRY_LOCATION_COMPACT: return new TriggerLocationCompactService(bookieServer); // autorecovery case AUTORECOVERY_STATUS: return new AutoRecoveryStatusService(configuration); case RECOVERY_BOOKIE: return new RecoveryBookieService(configuration, bka, executor); case LIST_UNDER_REPLICATED_LEDGER: return new ListUnderReplicatedLedgerService(configuration, ledgerManagerFactory); case WHO_IS_AUDITOR: return new WhoIsAuditorService(configuration, bka); case TRIGGER_AUDIT: return new TriggerAuditService(configuration, bka); case LOST_BOOKIE_RECOVERY_DELAY: return new LostBookieRecoveryDelayService(configuration, bka); case DECOMMISSION: return new DecommissionService(configuration, bka, executor); default: return new ConfigurationService(configuration); } } }
217
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/package-info.java
/* * 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 for bookkeeper http service. */ package org.apache.bookkeeper.server.http;
218
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/BookieIsReadyService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.StateManager; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; /** * HttpEndpointService that returns 200 if the bookie is ready. */ public class BookieIsReadyService implements HttpEndpointService { private final Bookie bookie; public BookieIsReadyService(Bookie bookie) { this.bookie = checkNotNull(bookie); } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET != request.getMethod()) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Only support GET method check if bookie is ready."); return response; } StateManager sm = bookie.getStateManager(); if (sm.isRunning() && !sm.isShuttingDown()) { response.setCode(HttpServer.StatusCode.OK); response.setBody("OK"); } else { response.setCode(HttpServer.StatusCode.SERVICE_UNAVAILABLE); response.setBody("Bookie is not fully started yet"); } return response; } }
219
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/ListDiskFilesService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.bookkeeper.bookie.BookieShell.listFilesAndSort; import com.google.common.collect.Maps; import java.io.File; import java.util.List; import java.util.Map; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper list disk files related http request. * * <p>The GET method will list all bookie files of type journal|entrylog|index in this bookie. * The output would be like this: * { * "journal files" : "filename1 \t ...", * "entrylog files" : "filename1 \t ...", * "index files" : "filename1 \t ..." * } */ public class ListDiskFilesService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(ListDiskFilesService.class); protected ServerConfiguration conf; public ListDiskFilesService(ServerConfiguration conf) { checkNotNull(conf); this.conf = conf; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); Map<String, String> params = request.getParams(); if (HttpServer.Method.GET == request.getMethod()) { /** * output: * { * "journal files" : "filename \t ...", * "entrylog files" : "filename \t ...", * "index files" : "filename \t ..." * } */ Map<String, String> output = Maps.newHashMap(); boolean journal = params != null && params.containsKey("file_type") && params.get("file_type").equals("journal"); boolean entrylog = params != null && params.containsKey("file_type") && params.get("file_type").equals("entrylog"); boolean index = params != null && params.containsKey("file_type") && params.get("file_type").equals("index"); boolean all = false; if (!journal && !entrylog && !index && !all) { all = true; } if (all || journal) { File[] journalDirs = conf.getJournalDirs(); List<File> journalFiles = listFilesAndSort(journalDirs, "txn"); StringBuilder files = new StringBuilder(); for (File journalFile : journalFiles) { files.append(journalFile.getName()).append("\t"); } output.put("journal files", files.toString()); } if (all || entrylog) { File[] ledgerDirs = conf.getLedgerDirs(); List<File> ledgerFiles = listFilesAndSort(ledgerDirs, "log"); StringBuilder files = new StringBuilder(); for (File ledgerFile : ledgerFiles) { files.append(ledgerFile.getName()).append("\t"); } output.put("entrylog files", files.toString()); } if (all || index) { File[] indexDirs = (conf.getIndexDirs() == null) ? conf.getLedgerDirs() : conf.getIndexDirs(); List<File> indexFiles = listFilesAndSort(indexDirs, "idx"); StringBuilder files = new StringBuilder(); for (File indexFile : indexFiles) { files.append(indexFile.getName()).append("\t"); } output.put("index files", files.toString()); } String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method"); return response; } } }
220
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/TriggerGCService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import java.util.HashMap; import java.util.Map; import org.apache.bookkeeper.bookie.LedgerStorage; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.proto.BookieServer; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle force trigger GC requests. * * <p>The PUT method will force trigger GC on current bookie, and make GC run at backend. * * <p>The GET method will get the force triggered GC running or not. * Output would be like: * { * "is_in_force_gc" : "false" * } */ public class TriggerGCService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(TriggerGCService.class); protected ServerConfiguration conf; protected BookieServer bookieServer; public TriggerGCService(ServerConfiguration conf, BookieServer bookieServer) { checkNotNull(conf); checkNotNull(bookieServer); this.conf = conf; this.bookieServer = bookieServer; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); try { if (HttpServer.Method.PUT == request.getMethod()) { String requestBody = request.getBody(); if (StringUtils.isBlank(requestBody)) { bookieServer.getBookie().getLedgerStorage().forceGC(); } else { @SuppressWarnings("unchecked") Map<String, Object> configMap = JsonUtil.fromJson(requestBody, HashMap.class); LedgerStorage ledgerStorage = bookieServer.getBookie().getLedgerStorage(); boolean forceMajor = !ledgerStorage.isMajorGcSuspended(); boolean forceMinor = !ledgerStorage.isMinorGcSuspended(); forceMajor = Boolean.parseBoolean(configMap.getOrDefault("forceMajor", forceMajor).toString()); forceMinor = Boolean.parseBoolean(configMap.getOrDefault("forceMinor", forceMinor).toString()); ledgerStorage.forceGC(forceMajor, forceMinor); } String output = "Triggered GC on BookieServer: " + bookieServer.getBookieId(); String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else if (HttpServer.Method.GET == request.getMethod()) { Boolean isInForceGC = bookieServer.getBookie().getLedgerStorage().isInForceGC(); Pair<String, String> output = Pair.of("is_in_force_gc", isInForceGC.toString()); String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.METHOD_NOT_ALLOWED); response.setBody("Not allowed method. Should be PUT to trigger GC, Or GET to get Force GC state."); return response; } } catch (Exception e) { LOG.error("Failed to handle the request, method: {}, body: {} ", request.getMethod(), request.getBody(), e); response.setCode(HttpServer.StatusCode.BAD_REQUEST); response.setBody("Failed to handle the request, exception: " + e.getMessage()); return response; } } }
221
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/ResumeCompactionService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import java.util.HashMap; import java.util.Map; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.proto.BookieServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResumeCompactionService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(ResumeCompactionService.class); protected BookieServer bookieServer; public ResumeCompactionService(BookieServer bookieServer) { checkNotNull(bookieServer); this.bookieServer = bookieServer; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.PUT == request.getMethod()) { String requestBody = request.getBody(); if (null == requestBody) { return new HttpServiceResponse("Empty request body", HttpServer.StatusCode.BAD_REQUEST); } else { @SuppressWarnings("unchecked") Map<String, Object> configMap = JsonUtil.fromJson(requestBody, HashMap.class); Boolean resumeMajor = (Boolean) configMap.get("resumeMajor"); Boolean resumeMinor = (Boolean) configMap.get("resumeMinor"); if (resumeMajor == null && resumeMinor == null) { return new HttpServiceResponse("No resumeMajor or resumeMinor params found", HttpServer.StatusCode.BAD_REQUEST); } String output = ""; if (resumeMajor != null && resumeMajor) { output = "Resume majorGC on BookieServer: " + bookieServer.toString(); bookieServer.getBookie().getLedgerStorage().resumeMajorGC(); } if (resumeMinor != null && resumeMinor) { output += ", Resume minorGC on BookieServer: " + bookieServer.toString(); bookieServer.getBookie().getLedgerStorage().resumeMinorGC(); } String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be PUT to resume major or minor compaction, Or GET to get " + "compaction state."); return response; } } }
222
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/BookieStateReadOnlyService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.StateManager; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; /** * HttpEndpointService that handles readOnly state related http requests. * The GET method will get the current readOnly state of the bookie. * The PUT method will change the current readOnly state of the bookie if the desired state is * different from the current. The request body could be {"readOnly":true/false}. The current * or the updated state will be included in the response. */ public class BookieStateReadOnlyService implements HttpEndpointService { private final Bookie bookie; public BookieStateReadOnlyService(Bookie bookie) { this.bookie = checkNotNull(bookie); } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); StateManager stateManager = this.bookie.getStateManager(); if (HttpServer.Method.PUT.equals(request.getMethod())) { ReadOnlyState inState = JsonUtil.fromJson(request.getBody(), ReadOnlyState.class); if (stateManager.isReadOnly() && !inState.isReadOnly()) { if (stateManager.isForceReadOnly()) { response.setCode(HttpServer.StatusCode.BAD_REQUEST); response.setBody("Bookie is in forceReadOnly mode, cannot transit to writable mode"); return response; } stateManager.transitionToWritableMode().get(); } else if (!stateManager.isReadOnly() && inState.isReadOnly()) { stateManager.transitionToReadOnlyMode().get(); } } else if (!HttpServer.Method.GET.equals(request.getMethod())) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Unsupported method. Should be GET or PUT method"); return response; } ReadOnlyState outState = new ReadOnlyState(stateManager.isReadOnly()); response.setBody(JsonUtil.toJson(outState)); response.setCode(HttpServer.StatusCode.OK); return response; } /** * The object represent the readOnly state. */ @AllArgsConstructor @NoArgsConstructor @Data public static class ReadOnlyState { private boolean readOnly; } }
223
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/SuspendCompactionService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import java.util.HashMap; import java.util.Map; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.proto.BookieServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SuspendCompactionService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(SuspendCompactionService.class); protected BookieServer bookieServer; public SuspendCompactionService(BookieServer bookieServer) { checkNotNull(bookieServer); this.bookieServer = bookieServer; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.PUT == request.getMethod()) { String requestBody = request.getBody(); if (null == requestBody) { return new HttpServiceResponse("Empty request body", HttpServer.StatusCode.BAD_REQUEST); } else { @SuppressWarnings("unchecked") Map<String, Object> configMap = JsonUtil.fromJson(requestBody, HashMap.class); Boolean suspendMajor = (Boolean) configMap.get("suspendMajor"); Boolean suspendMinor = (Boolean) configMap.get("suspendMinor"); if (suspendMajor == null && suspendMinor == null) { return new HttpServiceResponse("No suspendMajor or suspendMinor params found", HttpServer.StatusCode.BAD_REQUEST); } String output = ""; if (suspendMajor != null && suspendMajor) { output = "Suspend majorGC on BookieServer: " + bookieServer.toString(); bookieServer.getBookie().getLedgerStorage().suspendMajorGC(); } if (suspendMinor != null && suspendMinor) { output += ", Suspend minorGC on BookieServer: " + bookieServer.toString(); bookieServer.getBookie().getLedgerStorage().suspendMinorGC(); } String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } } else if (HttpServer.Method.GET == request.getMethod()) { boolean isMajorGcSuspend = bookieServer.getBookie().getLedgerStorage().isMajorGcSuspended(); boolean isMinorGcSuspend = bookieServer.getBookie().getLedgerStorage().isMinorGcSuspended(); Map<String, String> output = new HashMap<>(); output.put("isMajorGcSuspended", Boolean.toString(isMajorGcSuspend)); output.put("isMinorGcSuspended", Boolean.toString(isMinorGcSuspend)); String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be PUT to suspend major or minor compaction, " + "Or GET to get compaction state."); return response; } } }
224
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/GCDetailsService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import org.apache.bookkeeper.bookie.GarbageCollectionStatus; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.proto.BookieServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle get garbage collection details service. * * <p>Get Garbage Collection status, the output would be like: * [ { * "forceCompacting" : false, * "majorCompacting" : false, * "minorCompacting" : false, * "lastMajorCompactionTime" : 1544578144944, * "lastMinorCompactionTime" : 1544578144944, * "majorCompactionCounter" : 1, * "minorCompactionCounter" : 0 * } ] */ public class GCDetailsService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(GCDetailsService.class); protected ServerConfiguration conf; protected BookieServer bookieServer; public GCDetailsService(ServerConfiguration conf, BookieServer bookieServer) { checkNotNull(conf); checkNotNull(bookieServer); this.conf = conf; this.bookieServer = bookieServer; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET == request.getMethod()) { List<GarbageCollectionStatus> details = bookieServer.getBookie() .getLedgerStorage().getGarbageCollectionStatus(); String jsonResponse = JsonUtil.toJson(details); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Only support GET method to retrieve GC details." + " If you want to trigger gc, send a POST to gc endpoint."); return response; } } }
225
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/ListBookiesService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.Maps; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.net.BookieSocketAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper list bookies related http request. * The GET method will list all bookies of type rw|ro in this bookkeeper cluster. */ public class ListBookiesService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(ListBookiesService.class); protected ServerConfiguration conf; protected BookKeeperAdmin bka; public ListBookiesService(ServerConfiguration conf, BookKeeperAdmin bka) { checkNotNull(conf); this.conf = conf; this.bka = bka; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); // GET if (HttpServer.Method.GET == request.getMethod()) { Collection<BookieId> bookies = new ArrayList<BookieId>(); Map<String, String> params = request.getParams(); // default print rw boolean readOnly = (params != null) && params.containsKey("type") && params.get("type").equals("ro"); // default not print hostname boolean printHostname = (params != null) && params.containsKey("print_hostnames") && params.get("print_hostnames").equals("true"); if (readOnly) { bookies.addAll(bka.getReadOnlyBookies()); } else { bookies.addAll(bka.getAvailableBookies()); } // output <bookieSocketAddress: hostname> Map<String, String> output = Maps.newHashMap(); for (BookieId b : bookies) { String hostname = null; if (printHostname) { BookieSocketAddress resolved = bka.getBookieAddressResolver().resolve(b); hostname = resolved.getHostName(); } output.putIfAbsent(b.toString(), hostname); if (LOG.isDebugEnabled()) { LOG.debug("bookie: " + b + " hostname:" + hostname); } } String jsonResponse = JsonUtil.toJson(output); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method"); return response; } } }
226
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/ClusterInfoService.java
/* * 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.bookkeeper.server.http.service; import java.util.Iterator; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NonNull; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.meta.LedgerManagerFactory; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.bookkeeper.meta.UnderreplicatedLedger; import org.apache.bookkeeper.net.BookieId; /** * HttpEndpointService that exposes the current info about the cluster of bookies. * * <pre> * <code> * { * "hasAuditorElected" : true, * "auditorId" : "blah", * "hasUnderReplicatedLedgers": false, * "isLedgerReplicationEnabled": true, * "totalBookiesCount": 10, * "writableBookiesCount": 6, * "readonlyBookiesCount": 3, * "unavailableBookiesCount": 1 * } * </code> * </pre> */ @AllArgsConstructor @Slf4j public class ClusterInfoService implements HttpEndpointService { @NonNull private final BookKeeperAdmin bka; @NonNull private final LedgerManagerFactory ledgerManagerFactory; /** * POJO definition for the cluster info response. */ @Data public static class ClusterInfo { private boolean auditorElected; private String auditorId; private boolean clusterUnderReplicated; private boolean ledgerReplicationEnabled; private int totalBookiesCount; private int writableBookiesCount; private int readonlyBookiesCount; private int unavailableBookiesCount; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { final HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET != request.getMethod()) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Only GET is supported."); return response; } final ClusterInfo info = new ClusterInfo(); fillUReplicatedInfo(info); fillAuditorInfo(info); fillBookiesInfo(info); String jsonResponse = JsonUtil.toJson(info); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } @SneakyThrows private void fillBookiesInfo(ClusterInfo info) { int totalBookiesCount = bka.getAllBookies().size(); int writableBookiesCount = bka.getAvailableBookies().size(); int readonlyBookiesCount = bka.getReadOnlyBookies().size(); int unavailableBookiesCount = totalBookiesCount - writableBookiesCount - readonlyBookiesCount; info.setTotalBookiesCount(totalBookiesCount); info.setWritableBookiesCount(writableBookiesCount); info.setReadonlyBookiesCount(readonlyBookiesCount); info.setUnavailableBookiesCount(unavailableBookiesCount); } private void fillAuditorInfo(ClusterInfo info) { try { BookieId currentAuditor = bka.getCurrentAuditor(); info.setAuditorElected(currentAuditor != null); info.setAuditorId(currentAuditor == null ? "" : currentAuditor.getId()); } catch (Exception e) { log.error("Could not get Auditor info", e); info.setAuditorElected(false); info.setAuditorId(""); } } @SneakyThrows private void fillUReplicatedInfo(ClusterInfo info) { try (LedgerUnderreplicationManager underreplicationManager = ledgerManagerFactory.newLedgerUnderreplicationManager()) { Iterator<UnderreplicatedLedger> iter = underreplicationManager.listLedgersToRereplicate(null); info.setClusterUnderReplicated(iter.hasNext()); info.setLedgerReplicationEnabled(underreplicationManager.isLedgerReplicationEnabled()); } } }
227
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/RecoveryBookieService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithRegistrationManager; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.concurrent.ExecutorService; import org.apache.bookkeeper.bookie.Cookie; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.versioning.Versioned; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper recovery related http request. * * <p>The PUT method will recovery bookie with provided parameter. * The parameter of input body should be like this format: * { * "bookie_src": [ "bookie_src1", "bookie_src2"... ], * "delete_cookie": &lt;bool_value&gt; * } */ public class RecoveryBookieService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(RecoveryBookieService.class); protected ServerConfiguration conf; protected BookKeeperAdmin bka; protected ExecutorService executor; public RecoveryBookieService(ServerConfiguration conf, BookKeeperAdmin bka, ExecutorService executor) { checkNotNull(conf); this.conf = conf; this.bka = bka; this.executor = executor; } /* * Example body as this: * { * "bookie_src": [ "bookie_src1", "bookie_src2"... ], * "delete_cookie": <bool_value> * } */ static class RecoveryRequestJsonBody { @JsonProperty("bookie_src") public List<String> bookieSrc; @JsonProperty("delete_cookie") public boolean deleteCookie; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); String requestBody = request.getBody(); RecoveryRequestJsonBody requestJsonBody; if (requestBody == null) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("No request body provide."); return response; } try { requestJsonBody = JsonUtil.fromJson(requestBody, RecoveryRequestJsonBody.class); if (LOG.isDebugEnabled()) { LOG.debug("bookie_src: [" + requestJsonBody.bookieSrc.get(0) + "], delete_cookie: [" + requestJsonBody.deleteCookie + "]"); } } catch (JsonUtil.ParseJsonException e) { LOG.error("Meet Exception: ", e); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("ERROR parameters: " + e.getMessage()); return response; } if (HttpServer.Method.PUT == request.getMethod() && !requestJsonBody.bookieSrc.isEmpty()) { runFunctionWithRegistrationManager(conf, rm -> { final String bookieSrcSerialized = requestJsonBody.bookieSrc.get(0); executor.execute(() -> { try { BookieId bookieSrc = BookieId.parse(bookieSrcSerialized); boolean deleteCookie = requestJsonBody.deleteCookie; LOG.info("Start recovering bookie."); bka.recoverBookieData(bookieSrc); if (deleteCookie) { Versioned<Cookie> cookie = Cookie.readFromRegistrationManager(rm, bookieSrc); cookie.getValue().deleteFromRegistrationManager(rm, bookieSrc, cookie.getVersion()); } LOG.info("Complete recovering bookie"); } catch (Exception e) { LOG.error("Exception occurred while recovering bookie", e); } }); return null; }); response.setCode(HttpServer.StatusCode.OK); response.setBody("Success send recovery request command."); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be PUT method"); return response; } } }
228
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/ListUnderReplicatedLedgerService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.Lists; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.meta.LedgerManagerFactory; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.bookkeeper.meta.UnderreplicatedLedger; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper list under replicated ledger related http request. * * <p>The GET method will list all ledger_ids of under replicated ledger. * User can filer wanted ledger by set parameter "missingreplica" and "excludingmissingreplica" */ public class ListUnderReplicatedLedgerService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(ListUnderReplicatedLedgerService.class); protected ServerConfiguration conf; private final LedgerManagerFactory ledgerManagerFactory; public ListUnderReplicatedLedgerService(ServerConfiguration conf, LedgerManagerFactory ledgerManagerFactory) { checkNotNull(conf); this.conf = conf; this.ledgerManagerFactory = ledgerManagerFactory; } /* * Print the node which holds the auditor lock. */ @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); // parameter as this: ?missingreplica=<bookie_address>&excludingmissingreplica=<bookid_address> Map<String, String> params = request.getParams(); if (HttpServer.Method.GET == request.getMethod()) { final String includingBookieId; final String excludingBookieId; boolean printMissingReplica = false; if (params != null && params.containsKey("missingreplica")) { includingBookieId = params.get("missingreplica"); } else { includingBookieId = null; } if (params != null && params.containsKey("excludingmissingreplica")) { excludingBookieId = params.get("excludingmissingreplica"); } else { excludingBookieId = null; } if (params != null && params.containsKey("printmissingreplica")) { printMissingReplica = true; } Predicate<List<String>> predicate = null; if (!StringUtils.isBlank(includingBookieId) && !StringUtils.isBlank(excludingBookieId)) { predicate = replicasList -> (replicasList.contains(includingBookieId) && !replicasList.contains(excludingBookieId)); } else if (!StringUtils.isBlank(includingBookieId)) { predicate = replicasList -> replicasList.contains(includingBookieId); } else if (!StringUtils.isBlank(excludingBookieId)) { predicate = replicasList -> !replicasList.contains(excludingBookieId); } try { boolean hasURLedgers = false; List<Long> outputLedgers = null; Map<Long, List<String>> outputLedgersWithMissingReplica = null; LedgerUnderreplicationManager underreplicationManager = ledgerManagerFactory.newLedgerUnderreplicationManager(); Iterator<UnderreplicatedLedger> iter = underreplicationManager.listLedgersToRereplicate(predicate); hasURLedgers = iter.hasNext(); if (hasURLedgers) { if (printMissingReplica) { outputLedgersWithMissingReplica = new LinkedHashMap<Long, List<String>>(); } else { outputLedgers = Lists.newArrayList(); } } while (iter.hasNext()) { if (printMissingReplica) { UnderreplicatedLedger underreplicatedLedger = iter.next(); outputLedgersWithMissingReplica.put(underreplicatedLedger.getLedgerId(), underreplicatedLedger.getReplicaList()); } else { outputLedgers.add(iter.next().getLedgerId()); } } if (!hasURLedgers) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("No under replicated ledgers found"); return response; } else { response.setCode(HttpServer.StatusCode.OK); String jsonResponse = JsonUtil .toJson(printMissingReplica ? outputLedgersWithMissingReplica : outputLedgers); if (LOG.isDebugEnabled()) { LOG.debug("output body: " + jsonResponse); } response.setBody(jsonResponse); return response; } } catch (Exception e) { LOG.error("Exception occurred while listing under replicated ledgers", e); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Exception when get." + e.getMessage()); return response; } } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method"); return response; } } }
229
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/BookieSanityService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.tools.cli.commands.bookie.SanityTestCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that exposes the bookie sanity state. * * <p> * Get the current bookie sanity response: * * <pre> * <code> * { * "passed" : true, * "readOnly" : false *} * </code> * </pre> */ public class BookieSanityService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(BookieSanityService.class); private final ServerConfiguration config; private Semaphore lock = new Semaphore(1); private static final int TIMEOUT_MS = 5000; private static final int MAX_CONCURRENT_REQUESTS = 1; public BookieSanityService(ServerConfiguration config) { this.config = checkNotNull(config); } /** * POJO definition for the bookie sanity response. */ @Data @NoArgsConstructor public static class BookieSanity { private boolean passed; private boolean readOnly; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET != request.getMethod()) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Only support GET method to retrieve bookie sanity state."); return response; } BookieSanity bs = new BookieSanity(); if (config.isForceReadOnlyBookie()) { bs.readOnly = true; } else { try { // allow max concurrent request as sanity-test check relatively // longer time to complete try { lock.tryAcquire(MAX_CONCURRENT_REQUESTS, TIMEOUT_MS, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.error("Timing out due to max {} of sanity request are running concurrently", MAX_CONCURRENT_REQUESTS); response.setCode(HttpServer.StatusCode.INTERNAL_ERROR); response.setBody("Timing out due to max number of sanity request are running concurrently"); return response; } SanityTestCommand sanity = new SanityTestCommand(); bs.passed = sanity.apply(config, new SanityTestCommand.SanityFlags()); } finally { lock.release(); } } String jsonResponse = JsonUtil.toJson(bs); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } }
230
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/DecommissionService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import java.util.HashMap; import java.util.concurrent.ExecutorService; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.net.BookieId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper Decommission related http request. * The PUT method will send decommission bookie command running at backend. */ public class DecommissionService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(DecommissionService.class); protected ServerConfiguration conf; protected BookKeeperAdmin bka; protected ExecutorService executor; public DecommissionService(ServerConfiguration conf, BookKeeperAdmin bka, ExecutorService executor) { checkNotNull(conf); this.conf = conf; this.bka = bka; this.executor = executor; } /* * decommission bookie. */ @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.PUT == request.getMethod()) { String requestBody = request.getBody(); if (requestBody == null) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Null request body for DecommissionService."); return response; } @SuppressWarnings("unchecked") HashMap<String, String> configMap = JsonUtil.fromJson(requestBody, HashMap.class); if (configMap != null && configMap.containsKey("bookie_src")) { try { BookieId bookieSrc = BookieId.parse(configMap.get("bookie_src")); executor.execute(() -> { try { LOG.info("Start decommissioning bookie."); bka.decommissionBookie(bookieSrc); LOG.info("Complete decommissioning bookie."); } catch (Exception e) { LOG.error("Error handling decommissionBookie: {}.", bookieSrc, e); } }); response.setCode(HttpServer.StatusCode.OK); response.setBody("Success send decommission Bookie command " + bookieSrc); return response; } catch (Exception e) { LOG.error("Exception occurred while decommissioning bookie: ", e); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Exception when send decommission command." + e.getMessage()); return response; } } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Request body not contains bookie_src."); return response; } } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be PUT method"); return response; } } }
231
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/ReadLedgerEntryService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import static java.nio.charset.StandardCharsets.US_ASCII; import com.google.common.collect.Maps; import java.util.Iterator; import java.util.Map; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.client.LedgerEntry; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper read ledger entry related http request. * * <p>The GET method will print all entry content of wanted entry. * User should set wanted "ledger_id", and can choose only print out wanted entry * by set parameter "start_entry_id", "end_entry_id" and "page". */ public class ReadLedgerEntryService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(ReadLedgerEntryService.class); protected ServerConfiguration conf; protected BookKeeperAdmin bka; public ReadLedgerEntryService(ServerConfiguration conf, BookKeeperAdmin bka) { checkNotNull(conf); this.conf = conf; this.bka = bka; } static final Long ENTRIES_PER_PAE = 1000L; @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); Map<String, String> params = request.getParams(); if (HttpServer.Method.GET == request.getMethod() && (params != null) && params.containsKey("ledger_id")) { Long ledgerId = Long.parseLong(params.get("ledger_id")); Long startEntryId = 0L; Long endEntryId = -1L; if (params.containsKey("start_entry_id")) { startEntryId = Long.parseLong(params.get("start_entry_id")); } if (params.containsKey("end_entry_id")) { endEntryId = Long.parseLong(params.get("end_entry_id")); } // output <entryid: entry_content> Map<String, String> output = Maps.newHashMap(); // Page index should start from 1; Integer pageIndex = params.containsKey("page") ? Integer.parseInt(params.get("page")) : -1; if (pageIndex > 0) { // start and end ledger index for wanted page. Long startIndexInPage = (pageIndex - 1) * ENTRIES_PER_PAE; Long endIndexInPage = startIndexInPage + ENTRIES_PER_PAE - 1; if ((startEntryId == 0L) || (startEntryId < startIndexInPage)) { startEntryId = startIndexInPage; } if ((endEntryId == -1L) || (endEntryId > endIndexInPage)) { endEntryId = endIndexInPage; } output.put("Entries for page: ", pageIndex.toString()); } if (endEntryId != -1L && startEntryId > endEntryId) { response.setCode(HttpServer.StatusCode.INTERNAL_ERROR); response.setBody("parameter for start_entry_id: " + startEntryId + " and end_entry_id: " + endEntryId + " conflict with page=" + pageIndex); return response; } Iterator<LedgerEntry> entries = bka.readEntries(ledgerId, startEntryId, endEntryId).iterator(); while (entries.hasNext()) { LedgerEntry entry = entries.next(); output.put(Long.valueOf(entry.getEntryId()).toString(), new String(entry.getEntry(), US_ASCII)); } String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method, with ledger_id provided"); return response; } } }
232
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/AutoRecoveryStatusService.java
/* * 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.bookkeeper.server.http.service; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.UncheckedExecutionException; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Collections; import java.util.Map; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.bookkeeper.meta.MetadataDrivers; import org.apache.commons.lang3.ObjectUtils; /** * HttpEndpointService that handles Autorecovery status related http requests. * * <p></p>The GET method returns the current status of Autorecovery. The output would be like {"enabled" : true}. * * <p>The PUT method requires a parameter 'enabled', and enables Autorecovery if its value is 'true', * and disables Autorecovery otherwise. The behaviour is idempotent if Autorecovery status is already * the same as desired. The output would be the current status after the action. * */ @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") public class AutoRecoveryStatusService implements HttpEndpointService { protected final ServerConfiguration conf; public AutoRecoveryStatusService(ServerConfiguration conf) { this.conf = conf; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { return MetadataDrivers.runFunctionWithLedgerManagerFactory(conf, ledgerManagerFactory -> { try (LedgerUnderreplicationManager ledgerUnderreplicationManager = ledgerManagerFactory .newLedgerUnderreplicationManager()) { switch (request.getMethod()) { case GET: return handleGetStatus(ledgerUnderreplicationManager); case PUT: return handlePutStatus(request, ledgerUnderreplicationManager); default: return new HttpServiceResponse("Not found method. Should be GET or PUT method", HttpServer.StatusCode.NOT_FOUND); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new UncheckedExecutionException(e); } catch (Exception e) { throw new UncheckedExecutionException(e); } }); } private HttpServiceResponse handleGetStatus(LedgerUnderreplicationManager ledgerUnderreplicationManager) throws Exception { String body = JsonUtil.toJson(ImmutableMap.of("enabled", ledgerUnderreplicationManager.isLedgerReplicationEnabled())); return new HttpServiceResponse(body, HttpServer.StatusCode.OK); } private HttpServiceResponse handlePutStatus(HttpServiceRequest request, LedgerUnderreplicationManager ledgerUnderreplicationManager) throws Exception { Map<String, String> params = ObjectUtils.defaultIfNull(request.getParams(), Collections.emptyMap()); String enabled = params.get("enabled"); if (enabled == null) { return new HttpServiceResponse("Param 'enabled' not found in " + params, HttpServer.StatusCode.BAD_REQUEST); } if (Boolean.parseBoolean(enabled)) { if (!ledgerUnderreplicationManager.isLedgerReplicationEnabled()) { ledgerUnderreplicationManager.enableLedgerReplication(); } } else { if (ledgerUnderreplicationManager.isLedgerReplicationEnabled()) { ledgerUnderreplicationManager.disableLedgerReplication(); } } // use the current status as the response String body = JsonUtil.toJson(ImmutableMap.of("enabled", ledgerUnderreplicationManager.isLedgerReplicationEnabled())); return new HttpServiceResponse(body, HttpServer.StatusCode.OK); } }
233
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/TriggerLocationCompactService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.bookkeeper.bookie.LedgerStorage; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.proto.BookieServer; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle force trigger entry location compact requests. * * <p>The PUT method will trigger entry location compact on current bookie. * * <p>The GET method will get the entry location compact running or not. * Output would be like: * { * "/data1/bookkeeper/ledgers/current/locations" : "false", * "/data2/bookkeeper/ledgers/current/locations" : "true", * } */ public class TriggerLocationCompactService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(TriggerLocationCompactService.class); private final BookieServer bookieServer; private final List<String> entryLocationDBPath; public TriggerLocationCompactService(BookieServer bookieServer) { this.bookieServer = checkNotNull(bookieServer); this.entryLocationDBPath = bookieServer.getBookie().getLedgerStorage().getEntryLocationDBPath(); } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); LedgerStorage ledgerStorage = bookieServer.getBookie().getLedgerStorage(); if (HttpServer.Method.PUT.equals(request.getMethod())) { String requestBody = request.getBody(); String output = "Not trigger Entry Location RocksDB compact."; if (StringUtils.isBlank(requestBody)) { output = "Empty request body"; response.setBody(output); response.setCode(HttpServer.StatusCode.BAD_REQUEST); return response; } try { @SuppressWarnings("unchecked") Map<String, Object> configMap = JsonUtil.fromJson(requestBody, HashMap.class); Boolean isEntryLocationCompact = (Boolean) configMap .getOrDefault("entryLocationRocksDBCompact", false); String entryLocations = (String) configMap.getOrDefault("entryLocations", ""); if (!isEntryLocationCompact) { // If entryLocationRocksDBCompact is false, doing nothing. response.setBody(output); response.setCode(HttpServer.StatusCode.OK); return response; } if (StringUtils.isNotBlank(entryLocations)) { // Specified trigger RocksDB compact entryLocations. Set<String> locations = Sets.newHashSet(entryLocations.trim().split(",")); if (CollectionUtils.isSubCollection(locations, entryLocationDBPath)) { ledgerStorage.entryLocationCompact(Lists.newArrayList(locations)); output = String.format("Triggered entry Location RocksDB: %s compact on bookie:%s.", entryLocations, bookieServer.getBookieId()); response.setCode(HttpServer.StatusCode.OK); } else { output = String.format("Specified trigger compact entryLocations: %s is invalid. " + "Bookie entry location RocksDB path: %s.", entryLocations, entryLocationDBPath); response.setCode(HttpServer.StatusCode.BAD_REQUEST); } } else { // Not specified trigger compact entryLocations, trigger compact for all entry location. ledgerStorage.entryLocationCompact(); output = "Triggered entry Location RocksDB compact on bookie:" + bookieServer.getBookieId(); response.setCode(HttpServer.StatusCode.OK); } } catch (JsonUtil.ParseJsonException ex) { output = ex.getMessage(); response.setCode(HttpServer.StatusCode.BAD_REQUEST); LOG.warn("Trigger entry location index RocksDB compact failed, caused by: " + ex.getMessage()); } String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); return response; } else if (HttpServer.Method.GET == request.getMethod()) { Map<String, Boolean> compactStatus = ledgerStorage.isEntryLocationCompacting(entryLocationDBPath); String jsonResponse = JsonUtil.toJson(compactStatus); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.METHOD_NOT_ALLOWED); response.setBody("Not found method. Should be PUT to trigger entry location compact," + " Or GET to get entry location compact state."); return response; } } }
234
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/GetLastLogMarkService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.io.File; import java.util.List; import java.util.Map; import org.apache.bookkeeper.bookie.Journal; import org.apache.bookkeeper.bookie.LedgerDirsManager; import org.apache.bookkeeper.bookie.LogMark; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.util.DiskChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper get last log mark related http request. * The GET method will get the last log position of each journal. * * <p>output would be like this: * { * "&lt;Journal_id&gt;" : "&lt;Pos&gt;", * ... * } */ public class GetLastLogMarkService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(GetLastLogMarkService.class); protected ServerConfiguration conf; public GetLastLogMarkService(ServerConfiguration conf) { checkNotNull(conf); this.conf = conf; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET == request.getMethod()) { try { /** * output: * { * "&lt;Journal_id&gt;" : "&lt;Pos&gt;", * ... * } */ Map<String, String> output = Maps.newHashMap(); List<Journal> journals = Lists.newArrayListWithCapacity(conf.getJournalDirs().length); int idx = 0; for (File journalDir : conf.getJournalDirs()) { journals.add(new Journal(idx++, journalDir, conf, new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())))); } for (Journal journal : journals) { LogMark lastLogMark = journal.getLastLogMark().getCurMark(); if (LOG.isDebugEnabled()) { LOG.debug("LastLogMark: Journal Id - " + lastLogMark.getLogFileId() + "(" + Long.toHexString(lastLogMark.getLogFileId()) + ".txn), Pos - " + lastLogMark.getLogFileOffset()); } output.put("LastLogMark: Journal Id - " + lastLogMark.getLogFileId() + "(" + Long.toHexString(lastLogMark.getLogFileId()) + ".txn)", "Pos - " + lastLogMark.getLogFileOffset()); } String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } catch (Throwable e) { LOG.error("Exception occurred while getting last log mark", e); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("ERROR handling request: " + e.getMessage()); return response; } } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method"); return response; } } }
235
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/WhoIsAuditorService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.net.BookieId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper who is auditor related http request. * * <p>The GET method will get the auditor bookie address */ public class WhoIsAuditorService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(WhoIsAuditorService.class); protected ServerConfiguration conf; protected BookKeeperAdmin bka; public WhoIsAuditorService(ServerConfiguration conf, BookKeeperAdmin bka) { checkNotNull(conf); this.conf = conf; this.bka = bka; } /* * Print the node which holds the auditor lock. */ @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET == request.getMethod()) { BookieId bookieId; try { bookieId = bka.getCurrentAuditor(); if (bookieId == null) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("No auditor elected"); return response; } } catch (Exception e) { LOG.error("Meet Exception: ", e); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Exception when get." + e.getMessage()); return response; } response.setCode(HttpServer.StatusCode.OK); response.setBody("Auditor: " + bookieId); if (LOG.isDebugEnabled()) { LOG.debug("response body:" + response.getBody()); } return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method"); return response; } } }
236
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/LostBookieRecoveryDelayService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import java.util.HashMap; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper lost bookie recovery delay parameter related http request. * * <p>The GET method will get the value of parameter lostBookieRecoveryDelay, * while the PUT method will set the value of parameter lostBookieRecoveryDelay, */ public class LostBookieRecoveryDelayService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(LostBookieRecoveryDelayService.class); protected ServerConfiguration conf; protected BookKeeperAdmin bka; public LostBookieRecoveryDelayService(ServerConfiguration conf, BookKeeperAdmin bka) { checkNotNull(conf); this.conf = conf; this.bka = bka; } /* * set/get lostBookieRecoveryDelay. */ @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.PUT == request.getMethod()) { // request body as {"delay_seconds": <delay_seconds>} String requestBody = request.getBody(); if (requestBody == null) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Null request body for lostBookieRecoveryDelay."); return response; } @SuppressWarnings("unchecked") HashMap<String, Integer> configMap = JsonUtil.fromJson(requestBody, HashMap.class); if (configMap != null && configMap.containsKey("delay_seconds")) { int delaySeconds = configMap.get("delay_seconds"); bka.setLostBookieRecoveryDelay(delaySeconds); response.setCode(HttpServer.StatusCode.OK); response.setBody("Success set lostBookieRecoveryDelay to " + delaySeconds); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Request body not contains lostBookieRecoveryDelay."); return response; } } else if (HttpServer.Method.GET == request.getMethod()) { try { int delaySeconds = bka.getLostBookieRecoveryDelay(); response.setCode(HttpServer.StatusCode.OK); response.setBody("lostBookieRecoveryDelay value: " + delaySeconds); if (LOG.isDebugEnabled()) { LOG.debug("response body:" + response.getBody()); } return response; } catch (Exception e) { // may get noNode exception LOG.error("Exception occurred while getting lost bookie recovery delay", e); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Exception when get lostBookieRecoveryDelay." + e.getMessage()); return response; } } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be PUT method"); return response; } } }
237
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/ExpandStorageService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.Lists; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import java.net.URI; import java.util.Arrays; import java.util.List; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.LegacyCookieValidation; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.meta.MetadataBookieDriver; import org.apache.bookkeeper.meta.MetadataDrivers; import org.apache.bookkeeper.stats.NullStatsLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper expand storage related http request. * The PUT method will expand this bookie's storage. * User should update the directories info in the conf file with new empty ledger/index * directories, before running the command. */ public class ExpandStorageService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(ExpandStorageService.class); protected ServerConfiguration conf; public ExpandStorageService(ServerConfiguration conf) { checkNotNull(conf); this.conf = conf; } /* * Add new empty ledger/index directories. * Update the directories info in the conf file before running the command. */ @Override @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.PUT == request.getMethod()) { File[] ledgerDirectories = BookieImpl.getCurrentDirectories(conf.getLedgerDirs()); File[] journalDirectories = BookieImpl.getCurrentDirectories(conf.getJournalDirs()); File[] indexDirectories; if (null == conf.getIndexDirs()) { indexDirectories = ledgerDirectories; } else { indexDirectories = BookieImpl.getCurrentDirectories(conf.getIndexDirs()); } List<File> allLedgerDirs = Lists.newArrayList(); allLedgerDirs.addAll(Arrays.asList(ledgerDirectories)); if (indexDirectories != ledgerDirectories) { allLedgerDirs.addAll(Arrays.asList(indexDirectories)); } try (MetadataBookieDriver driver = MetadataDrivers.getBookieDriver( URI.create(conf.getMetadataServiceUri()))) { driver.initialize(conf, NullStatsLogger.INSTANCE); try (RegistrationManager registrationManager = driver.createRegistrationManager()) { LegacyCookieValidation validation = new LegacyCookieValidation(conf, registrationManager); List<File> dirs = Lists.newArrayList(journalDirectories); dirs.addAll(allLedgerDirs); validation.checkCookies(dirs); } } catch (BookieException e) { LOG.error("Exception occurred while updating cookie for storage expansion", e); response.setCode(HttpServer.StatusCode.INTERNAL_ERROR); response.setBody("Exception while updating cookie for storage expansion"); return response; } String jsonResponse = "Success expand storage"; if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be PUT method"); return response; } } }
238
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/ListBookieInfoService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.Maps; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.LinkedHashMap; import java.util.Map; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.BookieInfoReader; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.net.BookieId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper list bookie info related http request. * * <p>The GET method will get the disk usage of all bookies in this bookkeeper cluster. * Output would be like this: * { * "bookieAddress" : {free: xxx, total: xxx}", * "bookieAddress" : {free: xxx, total: xxx}, * ... * "clusterInfo" : {total_free: xxx, total: xxx}" * } */ public class ListBookieInfoService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(ListBookieInfoService.class); protected ServerConfiguration conf; public ListBookieInfoService(ServerConfiguration conf) { checkNotNull(conf); this.conf = conf; } String getReadable(long val) { String[] unit = {"", "KB", "MB", "GB", "TB" }; int cnt = 0; double d = val; while (d >= 1000 && cnt < unit.length - 1) { d = d / 1000; cnt++; } DecimalFormat df = new DecimalFormat("#.###"); df.setRoundingMode(RoundingMode.DOWN); return cnt > 0 ? "(" + df.format(d) + unit[cnt] + ")" : unit[cnt]; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET == request.getMethod()) { ClientConfiguration clientConf = new ClientConfiguration(conf); clientConf.setDiskWeightBasedPlacementEnabled(true); BookKeeper bk = new BookKeeper(clientConf); Map<BookieId, BookieInfoReader.BookieInfo> map = bk.getBookieInfo(); if (map.size() == 0) { bk.close(); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found any Bookie info."); return response; } /** * output: * { * "bookieAddress" : {free: xxx, total: xxx}", * "bookieAddress" : {free: xxx, total: xxx}, * ... * "clusterInfo" : {total_free: xxx, total: xxx}" * } */ LinkedHashMap<String, String> output = Maps.newLinkedHashMapWithExpectedSize(map.size()); Long totalFree = 0L, total = 0L; for (Map.Entry<BookieId, BookieInfoReader.BookieInfo> infoEntry : map.entrySet()) { BookieInfoReader.BookieInfo bInfo = infoEntry.getValue(); output.put(infoEntry.getKey().toString(), ": {Free: " + bInfo.getFreeDiskSpace() + getReadable(bInfo.getFreeDiskSpace()) + ", Total: " + bInfo.getTotalDiskSpace() + getReadable(bInfo.getTotalDiskSpace()) + "},"); totalFree += bInfo.getFreeDiskSpace(); total += bInfo.getTotalDiskSpace(); } output.put("ClusterInfo: ", "{Free: " + totalFree + getReadable(totalFree) + ", Total: " + total + getReadable(total) + "}"); bk.close(); String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method"); return response; } } }
239
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/ListLedgerService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.Maps; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.apache.bookkeeper.client.api.LedgerMetadata; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerManagerFactory; import org.apache.bookkeeper.meta.LedgerMetadataSerDe; import org.apache.bookkeeper.versioning.Versioned; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper list ledger related http request. * * <p>The GET method will list all ledger_ids in this bookkeeper cluster. * User can choose print metadata of each ledger or not by set parameter "print_metadata" */ public class ListLedgerService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(ListLedgerService.class); protected ServerConfiguration conf; protected LedgerManagerFactory ledgerManagerFactory; private final LedgerMetadataSerDe serDe; public ListLedgerService(ServerConfiguration conf, LedgerManagerFactory ledgerManagerFactory) { checkNotNull(conf); this.conf = conf; this.ledgerManagerFactory = ledgerManagerFactory; this.serDe = new LedgerMetadataSerDe(); } // Number of LedgerMetadata contains in each page static final int LIST_LEDGER_BATCH_SIZE = 100; private void keepLedgerMetadata(long ledgerId, CompletableFuture<Versioned<LedgerMetadata>> future, LinkedHashMap<String, Object> output, boolean decodeMeta) throws Exception { LedgerMetadata md = future.get().getValue(); if (decodeMeta) { output.put(Long.valueOf(ledgerId).toString(), md); } else { output.put(Long.valueOf(ledgerId).toString(), new String(serDe.serialize(md), UTF_8)); } } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); // GET // parameter could be like: print_metadata=true&page=PageIndex if (HttpServer.Method.GET == request.getMethod()) { Map<String, String> params = request.getParams(); // default not print metadata boolean printMeta = (params != null) && params.containsKey("print_metadata") && params.get("print_metadata").equals("true"); // do not decode meta by default for backward compatibility boolean decodeMeta = (params != null) && params.getOrDefault("decode_meta", "false").equals("true"); // Page index should start from 1; int pageIndex = (printMeta && params.containsKey("page")) ? Integer.parseInt(params.get("page")) : -1; LedgerManager manager = ledgerManagerFactory.newLedgerManager(); LedgerManager.LedgerRangeIterator iter = manager.getLedgerRanges(0); // output <ledgerId: ledgerMetadata> LinkedHashMap<String, Object> output = Maps.newLinkedHashMap(); // futures for readLedgerMetadata for each page. Map<Long, CompletableFuture<Versioned<LedgerMetadata>>> futures = new LinkedHashMap<>(LIST_LEDGER_BATCH_SIZE); if (printMeta) { int ledgerIndex = 0; // start and end ledger index for wanted page. int startLedgerIndex = 0; int endLedgerIndex = 0; if (pageIndex > 0) { startLedgerIndex = (pageIndex - 1) * LIST_LEDGER_BATCH_SIZE; endLedgerIndex = startLedgerIndex + LIST_LEDGER_BATCH_SIZE - 1; } // get metadata while (iter.hasNext()) { LedgerManager.LedgerRange r = iter.next(); for (Long lid : r.getLedgers()) { ledgerIndex++; if (endLedgerIndex == 0 // no actual page parameter provided || (ledgerIndex >= startLedgerIndex && ledgerIndex <= endLedgerIndex)) { futures.put(lid, manager.readLedgerMetadata(lid)); } } if (futures.size() >= LIST_LEDGER_BATCH_SIZE) { for (Map.Entry<Long, CompletableFuture<Versioned<LedgerMetadata>> > e : futures.entrySet()) { keepLedgerMetadata(e.getKey(), e.getValue(), output, decodeMeta); } futures.clear(); } } for (Map.Entry<Long, CompletableFuture<Versioned<LedgerMetadata>> > e : futures.entrySet()) { keepLedgerMetadata(e.getKey(), e.getValue(), output, decodeMeta); } futures.clear(); } else { while (iter.hasNext()) { LedgerManager.LedgerRange r = iter.next(); for (Long lid : r.getLedgers()) { output.put(lid.toString(), null); } } } manager.close(); String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method"); return response; } } }
240
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/MetricsService.java
/* * 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.bookkeeper.server.http.service; import java.io.IOException; import java.io.StringWriter; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer.Method; import org.apache.bookkeeper.http.HttpServer.StatusCode; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.stats.StatsProvider; /** * HttpEndpointService that handle exposing metrics. * * <p>The GET method will return all the emtrics collected at stats provider. */ public class MetricsService implements HttpEndpointService { private final ServerConfiguration conf; private final StatsProvider statsProvider; public MetricsService(ServerConfiguration conf, StatsProvider statsProvider) { this.conf = conf; this.statsProvider = statsProvider; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (Method.GET != request.getMethod()) { response.setCode(StatusCode.FORBIDDEN); response.setBody(request.getMethod() + " is forbidden. Should be GET method"); return response; } if (null == statsProvider) { response.setCode(StatusCode.INTERNAL_ERROR); response.setBody("Stats provider is not enabled. Please enable it by set statsProviderClass" + " on bookie configuration"); return response; } // GET try (StringWriter writer = new StringWriter(1024)) { statsProvider.writeAllMetrics(writer); writer.flush(); response.setCode(StatusCode.OK); response.setBody(writer.getBuffer().toString()); } catch (UnsupportedOperationException uoe) { response.setCode(StatusCode.INTERNAL_ERROR); response.setBody("Currently stats provider doesn't support exporting metrics in http service"); } catch (IOException ioe) { response.setCode(StatusCode.INTERNAL_ERROR); response.setBody("Exceptions are thrown when exporting metrics : " + ioe.getMessage()); } return response; } }
241
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/BookieStateService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.StateManager; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; /** * HttpEndpointService that exposes the current state of the bookie. * * <p>Get the current bookie status: * * <pre> * <code> * { * "running" : true, * "readOnly" : false, * "shuttingDown" : false, * "availableForHighPriorityWrites" : true *} * </code> * </pre> */ public class BookieStateService implements HttpEndpointService { private final Bookie bookie; public BookieStateService(Bookie bookie) { this.bookie = checkNotNull(bookie); } /** * POJO definition for the bookie state response. */ @Data @NoArgsConstructor public static class BookieState { private boolean running; private boolean readOnly; private boolean shuttingDown; private boolean availableForHighPriorityWrites; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET != request.getMethod()) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Only support GET method to retrieve bookie state."); return response; } StateManager sm = bookie.getStateManager(); BookieState bs = new BookieState(); bs.running = sm.isRunning(); bs.readOnly = sm.isReadOnly(); bs.shuttingDown = sm.isShuttingDown(); bs.availableForHighPriorityWrites = sm.isAvailableForHighPriorityWrites(); String jsonResponse = JsonUtil.toJson(bs); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } }
242
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/DeleteLedgerService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Map; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper delete ledger related http request. * The DELETE method will delete ledger with provided "ledger_id". */ public class DeleteLedgerService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(DeleteLedgerService.class); protected ServerConfiguration conf; public DeleteLedgerService(ServerConfiguration conf) { checkNotNull(conf); this.conf = conf; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); // only handle DELETE method if (HttpServer.Method.DELETE == request.getMethod()) { Map<String, String> params = request.getParams(); if (params != null && params.containsKey("ledger_id")) { ClientConfiguration clientConf = new ClientConfiguration(); clientConf.addConfiguration(conf); BookKeeper bk = new BookKeeper(clientConf); Long ledgerId = Long.parseLong(params.get("ledger_id")); bk.deleteLedger(ledgerId); String output = "Deleted ledger: " + ledgerId; String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not ledger found. Should provide ledger_id=<id>"); return response; } } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be DELETE method"); return response; } } }
243
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/ConfigurationService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import java.util.HashMap; import java.util.Map; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; /** * HttpEndpointService that handle Bookkeeper Configuration related http request. */ public class ConfigurationService implements HttpEndpointService { protected ServerConfiguration conf; public ConfigurationService(ServerConfiguration conf) { checkNotNull(conf); this.conf = conf; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); // GET if (HttpServer.Method.GET == request.getMethod()) { String jsonResponse = conf.asJson(); response.setBody(jsonResponse); return response; } else if (HttpServer.Method.PUT == request.getMethod()) { String requestBody = request.getBody(); if (null == requestBody) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Request body not found. should contains k-v pairs"); return response; } @SuppressWarnings("unchecked") HashMap<String, Object> configMap = JsonUtil.fromJson(requestBody, HashMap.class); for (Map.Entry<String, Object> entry: configMap.entrySet()) { conf.setProperty(entry.getKey(), entry.getValue()); } response.setCode(HttpServer.StatusCode.OK); response.setBody("Success set server config."); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Request body not found. should contains k-v pairs"); return response; } } }
244
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/GetLedgerMetaService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.Maps; import java.util.Map; import org.apache.bookkeeper.client.api.LedgerMetadata; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerManagerFactory; import org.apache.bookkeeper.meta.LedgerMetadataSerDe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper get ledger metadata related http request. * The GET method will get the ledger metadata for given "ledger_id". */ public class GetLedgerMetaService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(GetLedgerMetaService.class); protected ServerConfiguration conf; private final LedgerManagerFactory ledgerManagerFactory; private final LedgerMetadataSerDe serDe; public GetLedgerMetaService(ServerConfiguration conf, LedgerManagerFactory ledgerManagerFactory) { checkNotNull(conf); this.conf = conf; this.ledgerManagerFactory = ledgerManagerFactory; this.serDe = new LedgerMetadataSerDe(); } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); Map<String, String> params = request.getParams(); if (HttpServer.Method.GET == request.getMethod() && (params != null) && params.containsKey("ledger_id")) { Long ledgerId = Long.parseLong(params.get("ledger_id")); LedgerManager manager = ledgerManagerFactory.newLedgerManager(); // output <ledgerId: ledgerMetadata> Map<String, Object> output = Maps.newHashMap(); LedgerMetadata md = manager.readLedgerMetadata(ledgerId).get().getValue(); output.put(ledgerId.toString(), md); manager.close(); String jsonResponse = JsonUtil.toJson(output); if (LOG.isDebugEnabled()) { LOG.debug("output body:" + jsonResponse); } response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method"); return response; } } }
245
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/BookieInfoService.java
/* * 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.bookkeeper.server.http.service; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; /** * HttpEndpointService that exposes the current info of the bookie. * * <pre> * <code> * { * "freeSpace" : 0, * "totalSpace" : 0 * } * </code> * </pre> */ @AllArgsConstructor public class BookieInfoService implements HttpEndpointService { @NonNull private final Bookie bookie; /** * POJO definition for the bookie info response. */ @Data @NoArgsConstructor @AllArgsConstructor public static class BookieInfo { private long freeSpace; private long totalSpace; } @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET != request.getMethod()) { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Only GET is supported."); return response; } BookieInfo bi = new BookieInfo(bookie.getTotalFreeSpace(), bookie.getTotalDiskSpace()); String jsonResponse = JsonUtil.toJson(bi); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } }
246
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/TriggerAuditService.java
/* * 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.bookkeeper.server.http.service; import static com.google.common.base.Preconditions.checkNotNull; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.service.HttpEndpointService; import org.apache.bookkeeper.http.service.HttpServiceRequest; import org.apache.bookkeeper.http.service.HttpServiceResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HttpEndpointService that handle Bookkeeper trigger audit related http request. * The PUT method will force trigger the audit by resetting the lostBookieRecoveryDelay. */ public class TriggerAuditService implements HttpEndpointService { static final Logger LOG = LoggerFactory.getLogger(TriggerAuditService.class); protected ServerConfiguration conf; protected BookKeeperAdmin bka; public TriggerAuditService(ServerConfiguration conf, BookKeeperAdmin bka) { checkNotNull(conf); this.conf = conf; this.bka = bka; } /* * Force trigger the Audit by resetting the lostBookieRecoveryDelay. */ @Override public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.PUT == request.getMethod()) { try { bka.triggerAudit(); } catch (Exception e) { LOG.error("Meet Exception: ", e); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Exception when do operation." + e.getMessage()); return response; } response.setCode(HttpServer.StatusCode.OK); response.setBody("Success trigger audit."); if (LOG.isDebugEnabled()) { LOG.debug("response body:" + response.getBody()); } return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be PUT method"); return response; } } }
247
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/http/service/package-info.java
/* * 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. */ /** * Define the services running in bookkeeper admin http server. */ package org.apache.bookkeeper.server.http.service;
248
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/service/ScrubberService.java
/* * * 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.bookkeeper.server.service; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.bookkeeper.bookie.ScrubberStats.DETECTED_FATAL_SCRUB_ERRORS; import static org.apache.bookkeeper.bookie.ScrubberStats.DETECTED_SCRUB_ERRORS; import static org.apache.bookkeeper.bookie.ScrubberStats.RUN_DURATION; import com.google.common.util.concurrent.RateLimiter; import io.netty.util.concurrent.DefaultThreadFactory; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.bookkeeper.bookie.ExitCode; import org.apache.bookkeeper.bookie.LedgerStorage; import org.apache.bookkeeper.server.component.ServerLifecycleComponent; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.bookkeeper.stats.Counter; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A {@link org.apache.bookkeeper.common.component.LifecycleComponent} that runs the scrubber background service. */ public class ScrubberService extends ServerLifecycleComponent { private static final Logger LOG = LoggerFactory.getLogger(ScrubberService.class); private static final String NAME = "scrubber"; private final ScheduledExecutorService executor; private final Random rng = new Random(); private final long scrubPeriod; private final Optional<RateLimiter> scrubRateLimiter; private final AtomicBoolean stop = new AtomicBoolean(false); private final LedgerStorage ledgerStorage; private final OpStatsLogger scrubCounter; private final Counter errorCounter; private final Counter fatalErrorCounter; public ScrubberService( StatsLogger logger, BookieConfiguration conf, LedgerStorage ledgerStorage) { super(NAME, conf, logger); this.executor = Executors.newSingleThreadScheduledExecutor( new DefaultThreadFactory("ScrubThread")); this.scrubPeriod = conf.getServerConf().getLocalScrubPeriod(); checkArgument( scrubPeriod > 0, "localScrubInterval must be > 0 for ScrubberService to be used"); double rateLimit = conf.getServerConf().getLocalScrubRateLimit(); this.scrubRateLimiter = rateLimit == 0 ? Optional.empty() : Optional.of(RateLimiter.create(rateLimit)); this.ledgerStorage = ledgerStorage; this.scrubCounter = logger.getOpStatsLogger(RUN_DURATION); this.errorCounter = logger.getCounter(DETECTED_SCRUB_ERRORS); this.fatalErrorCounter = logger.getCounter(DETECTED_FATAL_SCRUB_ERRORS); } private long getNextPeriodMS() { return (long) (((double) scrubPeriod) * (1.5 - rng.nextDouble()) * 1000); } private void doSchedule() { executor.schedule( this::run, getNextPeriodMS(), TimeUnit.MILLISECONDS); } private void run() { boolean success = false; long start = MathUtils.nowInNano(); try { List<LedgerStorage.DetectedInconsistency> errors = ledgerStorage.localConsistencyCheck(scrubRateLimiter); if (errors.size() > 0) { errorCounter.addCount(errors.size()); LOG.error("Found inconsistency during localConsistencyCheck:"); for (LedgerStorage.DetectedInconsistency error : errors) { LOG.error("Ledger {}, entry {}: ", error.getLedgerId(), error.getEntryId(), error.getException()); } } success = true; } catch (IOException e) { fatalErrorCounter.inc(); LOG.error("Got fatal exception {} running localConsistencyCheck", e.toString()); } if (success) { scrubCounter.registerSuccessfulEvent(MathUtils.elapsedNanos(start), TimeUnit.NANOSECONDS); } else { scrubCounter.registerFailedEvent(MathUtils.elapsedNanos(start), TimeUnit.NANOSECONDS); Runtime.getRuntime().exit(ExitCode.BOOKIE_EXCEPTION); } if (!stop.get()) { doSchedule(); } } @Override protected void doStart() { doSchedule(); } @Override protected void doStop() { stop.set(true); executor.shutdown(); } @Override protected void doClose() throws IOException { // no-op } }
249
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/service/BookieService.java
/* * 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.bookkeeper.server.service; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.UncleanShutdownDetection; import org.apache.bookkeeper.common.allocator.ByteBufAllocatorWithOomHandler; import org.apache.bookkeeper.common.component.ComponentInfoPublisher; import org.apache.bookkeeper.common.component.ComponentInfoPublisher.EndpointInfo; import org.apache.bookkeeper.net.BookieSocketAddress; import org.apache.bookkeeper.proto.BookieServer; import org.apache.bookkeeper.server.component.ServerLifecycleComponent; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.bookkeeper.stats.StatsLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A {@link ServerLifecycleComponent} that starts the core bookie server. */ public class BookieService extends ServerLifecycleComponent { private static final Logger log = LoggerFactory.getLogger(BookieService.class); public static final String NAME = "bookie-server"; private final BookieServer server; private final ByteBufAllocatorWithOomHandler allocator; public BookieService(BookieConfiguration conf, Bookie bookie, StatsLogger statsLogger, ByteBufAllocatorWithOomHandler allocator, UncleanShutdownDetection uncleanShutdownDetection) throws Exception { super(NAME, conf, statsLogger); this.server = new BookieServer(conf.getServerConf(), bookie, statsLogger, allocator, uncleanShutdownDetection); this.allocator = allocator; } @Override public void setExceptionHandler(UncaughtExceptionHandler handler) { super.setExceptionHandler(handler); server.setExceptionHandler(handler); allocator.setOomHandler((ex) -> { try { log.error("Unable to allocate memory, exiting bookie", ex); } finally { if (uncaughtExceptionHandler != null) { uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), ex); } } }); } public BookieServer getServer() { return server; } @Override protected void doStart() { try { this.server.start(); } catch (InterruptedException | IOException exc) { throw new RuntimeException("Failed to start bookie server", exc); } } @Override protected void doStop() { // no-op } @Override protected void doClose() throws IOException { this.server.shutdown(); } @Override public void publishInfo(ComponentInfoPublisher componentInfoPublisher) { try { BookieSocketAddress localAddress = getServer().getLocalAddress(); List<String> extensions = new ArrayList<>(); if (conf.getServerConf().getTLSProviderFactoryClass() != null) { extensions.add("tls"); } EndpointInfo endpoint = new EndpointInfo("bookie", localAddress.getPort(), localAddress.getHostName(), "bookie-rpc", null, extensions); componentInfoPublisher.publishEndpoint(endpoint); } catch (UnknownHostException err) { log.error("Cannot compute local address", err); } } }
250
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/service/StatsProviderService.java
/* * 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.bookkeeper.server.service; import java.io.IOException; import org.apache.bookkeeper.common.util.ReflectionUtils; import org.apache.bookkeeper.server.component.ServerLifecycleComponent; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.StatsProvider; /** * A {@link org.apache.bookkeeper.common.component.LifecycleComponent} that runs stats provider. */ public class StatsProviderService extends ServerLifecycleComponent { public static final String NAME = "stats-provider"; private final StatsProvider statsProvider; public StatsProviderService(BookieConfiguration conf) throws Exception { super(NAME, conf, NullStatsLogger.INSTANCE); Class<? extends StatsProvider> statsProviderClass = conf.getServerConf().getStatsProviderClass(); this.statsProvider = ReflectionUtils.newInstance(statsProviderClass); } public StatsProvider getStatsProvider() { return this.statsProvider; } @Override protected void doStart() { statsProvider.start(conf); } @Override protected void doStop() { statsProvider.stop(); } @Override protected void doClose() throws IOException { // no-op } }
251
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/service/AutoRecoveryService.java
/* * 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.bookkeeper.server.service; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import org.apache.bookkeeper.replication.AutoRecoveryMain; import org.apache.bookkeeper.server.component.ServerLifecycleComponent; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.bookkeeper.stats.StatsLogger; /** * A {@link ServerLifecycleComponent} that runs autorecovery. */ public class AutoRecoveryService extends ServerLifecycleComponent { public static final String NAME = "autorecovery"; private final AutoRecoveryMain main; public AutoRecoveryService(BookieConfiguration conf, StatsLogger statsLogger) throws Exception { super(NAME, conf, statsLogger); this.main = new AutoRecoveryMain( conf.getServerConf(), statsLogger); } @Override public void setExceptionHandler(UncaughtExceptionHandler handler) { super.setExceptionHandler(handler); main.setExceptionHandler(handler); } public AutoRecoveryMain getAutoRecoveryServer() { return main; } @Override protected void doStart() { this.main.start(); } @Override protected void doStop() { // no-op } @Override protected void doClose() throws IOException { this.main.shutdown(); } }
252
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/service/HttpService.java
/* * 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.bookkeeper.server.service; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import org.apache.bookkeeper.common.component.ComponentInfoPublisher; import org.apache.bookkeeper.common.component.ComponentInfoPublisher.EndpointInfo; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.http.HttpServer; import org.apache.bookkeeper.http.HttpServerConfiguration; import org.apache.bookkeeper.http.HttpServerLoader; import org.apache.bookkeeper.server.component.ServerLifecycleComponent; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.bookkeeper.server.http.BKHttpServiceProvider; import org.apache.bookkeeper.stats.StatsLogger; /** * A {@link ServerLifecycleComponent} that runs http service. */ public class HttpService extends ServerLifecycleComponent { public static final String NAME = "http-service"; private HttpServer server; public HttpService(BKHttpServiceProvider provider, BookieConfiguration conf, StatsLogger statsLogger) { super(NAME, conf, statsLogger); HttpServerLoader.loadHttpServer(conf.getServerConf()); server = HttpServerLoader.get(); checkNotNull(server, "httpServerClass is not configured or it could not be started," + " please check your configuration and logs"); server.initialize(provider); } @Override protected void doStart() { ServerConfiguration serverConf = conf.getServerConf(); HttpServerConfiguration tlsOption = new HttpServerConfiguration(serverConf.isHttpServerTlsEnable(), serverConf.getHttpServerKeystorePath(), serverConf.getHttpServerKeystorePassword(), serverConf.getHttpServerTrustStorePath(), serverConf.getHttpServerTrustStorePassword()); server.startServer(serverConf.getHttpServerPort(), serverConf.getHttpServerHost(), tlsOption); } @Override protected void doStop() { // no-op } @Override protected void doClose() throws IOException { server.stopServer(); } @Override public void publishInfo(ComponentInfoPublisher componentInfoPublisher) { if (conf.getServerConf().isHttpServerEnabled()) { EndpointInfo endpoint = new EndpointInfo("httpserver", conf.getServerConf().getHttpServerPort(), "0.0.0.0", "http", null, null); componentInfoPublisher.publishEndpoint(endpoint); } } }
253
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/service/package-info.java
/* * 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. */ /** * Services running in a storage server (bookie). */ package org.apache.bookkeeper.server.service;
254
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/conf/BookieConfiguration.java
/* * 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.bookkeeper.server.conf; import org.apache.bookkeeper.common.conf.ComponentConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; /** * A bookie related {@link ComponentConfiguration}. */ public class BookieConfiguration extends ComponentConfiguration { private final ServerConfiguration serverConf; public BookieConfiguration(ServerConfiguration conf) { super(conf, ""); this.serverConf = conf; } public ServerConfiguration getServerConf() { return this.serverConf; } }
255
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/server/conf/package-info.java
/* * 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. */ /** * Server component related configuration. */ package org.apache.bookkeeper.server.conf;
256
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/zookeeper/BoundExponentialBackoffRetryPolicy.java
/* * * 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.bookkeeper.zookeeper; /** * Retry policy that retries a set number of times with an increasing (up to a * maximum bound) backoff time between retries. */ public class BoundExponentialBackoffRetryPolicy extends ExponentialBackoffRetryPolicy { private final long maxBackoffTime; public BoundExponentialBackoffRetryPolicy(long baseBackoffTime, long maxBackoffTime, int maxRetries) { super(baseBackoffTime, maxRetries); this.maxBackoffTime = maxBackoffTime; } @Override public long nextRetryWaitTime(int retryCount, long elapsedRetryTime) { return Math.min(maxBackoffTime, super.nextRetryWaitTime(retryCount, elapsedRetryTime)); } }
257
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/zookeeper/ZooKeeperClient.java
/* * * 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.bookkeeper.zookeeper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.RateLimiter; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.zookeeper.ZooWorker.ZooCallable; import org.apache.zookeeper.AsyncCallback.ACLCallback; import org.apache.zookeeper.AsyncCallback.Children2Callback; import org.apache.zookeeper.AsyncCallback.ChildrenCallback; import org.apache.zookeeper.AsyncCallback.DataCallback; import org.apache.zookeeper.AsyncCallback.MultiCallback; import org.apache.zookeeper.AsyncCallback.StatCallback; import org.apache.zookeeper.AsyncCallback.StringCallback; import org.apache.zookeeper.AsyncCallback.VoidCallback; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Op; import org.apache.zookeeper.OpResult; import org.apache.zookeeper.Transaction; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provide a zookeeper client to handle session expire. */ public class ZooKeeperClient extends ZooKeeper implements Watcher, AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(ZooKeeperClient.class); private static final int DEFAULT_RETRY_EXECUTOR_THREAD_COUNT = 1; // ZooKeeper client connection variables private final String connectString; private final int sessionTimeoutMs; private final boolean allowReadOnlyMode; // state for the zookeeper client private final AtomicReference<ZooKeeper> zk = new AtomicReference<ZooKeeper>(); private final AtomicBoolean closed = new AtomicBoolean(false); private final ZooKeeperWatcherBase watcherManager; private final ScheduledExecutorService retryExecutor; private final ExecutorService connectExecutor; // rate limiter private final RateLimiter rateLimiter; // retry polices private final RetryPolicy connectRetryPolicy; private final RetryPolicy operationRetryPolicy; // Stats Logger private final OpStatsLogger createStats; private final OpStatsLogger getStats; private final OpStatsLogger setStats; private final OpStatsLogger deleteStats; private final OpStatsLogger getChildrenStats; private final OpStatsLogger existsStats; private final OpStatsLogger multiStats; private final OpStatsLogger getACLStats; private final OpStatsLogger setACLStats; private final OpStatsLogger syncStats; private final OpStatsLogger createClientStats; private final Callable<ZooKeeper> clientCreator = new Callable<ZooKeeper>() { @Override public ZooKeeper call() throws Exception { try { return ZooWorker.syncCallWithRetries(null, new ZooCallable<ZooKeeper>() { @Override public ZooKeeper call() throws KeeperException, InterruptedException { logger.info("Reconnecting zookeeper {}.", connectString); // close the previous one closeZkHandle(); ZooKeeper newZk; try { newZk = createZooKeeper(); } catch (IOException ie) { logger.error("Failed to create zookeeper instance to " + connectString, ie); throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS); } waitForConnection(); zk.set(newZk); logger.info("ZooKeeper session {} is created to {}.", Long.toHexString(newZk.getSessionId()), connectString); return newZk; } @Override public String toString() { return String.format("ZooKeeper Client Creator (%s)", connectString); } }, connectRetryPolicy, rateLimiter, createClientStats); } catch (Exception e) { logger.error("Gave up reconnecting to ZooKeeper : ", e); Runtime.getRuntime().exit(-1); return null; } } }; @VisibleForTesting static ZooKeeperClient createConnectedZooKeeperClient( String connectString, int sessionTimeoutMs, Set<Watcher> childWatchers, RetryPolicy operationRetryPolicy) throws KeeperException, InterruptedException, IOException { return ZooKeeperClient.newBuilder() .connectString(connectString) .sessionTimeoutMs(sessionTimeoutMs) .watchers(childWatchers) .operationRetryPolicy(operationRetryPolicy) .build(); } /** * A builder to build retryable zookeeper client. */ public static class Builder { String connectString = null; int sessionTimeoutMs = 10000; Set<Watcher> watchers = null; RetryPolicy connectRetryPolicy = null; RetryPolicy operationRetryPolicy = null; StatsLogger statsLogger = NullStatsLogger.INSTANCE; int retryExecThreadCount = DEFAULT_RETRY_EXECUTOR_THREAD_COUNT; double requestRateLimit = 0; boolean allowReadOnlyMode = false; private Builder() {} public Builder connectString(String connectString) { this.connectString = connectString; return this; } public Builder sessionTimeoutMs(int sessionTimeoutMs) { this.sessionTimeoutMs = sessionTimeoutMs; return this; } public Builder watchers(Set<Watcher> watchers) { this.watchers = watchers; return this; } public Builder connectRetryPolicy(RetryPolicy retryPolicy) { this.connectRetryPolicy = retryPolicy; return this; } public Builder operationRetryPolicy(RetryPolicy retryPolicy) { this.operationRetryPolicy = retryPolicy; return this; } public Builder statsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } public Builder requestRateLimit(double requestRateLimit) { this.requestRateLimit = requestRateLimit; return this; } public Builder retryThreadCount(int numThreads) { this.retryExecThreadCount = numThreads; return this; } public Builder allowReadOnlyMode(boolean allowReadOnlyMode) { this.allowReadOnlyMode = allowReadOnlyMode; return this; } public ZooKeeperClient build() throws IOException, KeeperException, InterruptedException { checkNotNull(connectString); checkArgument(sessionTimeoutMs > 0); checkNotNull(statsLogger); checkArgument(retryExecThreadCount > 0); if (null == connectRetryPolicy) { // Session expiry event is received by client only when zk quorum is well established. // All other connection loss retries happen at zk client library transparently. // Hence, we don't need to wait before retrying. connectRetryPolicy = new BoundExponentialBackoffRetryPolicy(0, 0, Integer.MAX_VALUE); } if (null == operationRetryPolicy) { operationRetryPolicy = new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, 0); } // Create a watcher manager StatsLogger watcherStatsLogger = statsLogger.scope("watcher"); ZooKeeperWatcherBase watcherManager = null == watchers ? new ZooKeeperWatcherBase(sessionTimeoutMs, watcherStatsLogger) : new ZooKeeperWatcherBase(sessionTimeoutMs, watchers, watcherStatsLogger); ZooKeeperClient client = new ZooKeeperClient( connectString, sessionTimeoutMs, watcherManager, connectRetryPolicy, operationRetryPolicy, statsLogger, retryExecThreadCount, requestRateLimit, allowReadOnlyMode ); // Wait for connection to be established. try { watcherManager.waitForConnection(); } catch (KeeperException ke) { client.close(); throw ke; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); client.close(); throw ie; } return client; } } public static Builder newBuilder() { return new Builder(); } protected ZooKeeperClient(String connectString, int sessionTimeoutMs, ZooKeeperWatcherBase watcherManager, RetryPolicy connectRetryPolicy, RetryPolicy operationRetryPolicy, StatsLogger statsLogger, int retryExecThreadCount, double rate, boolean allowReadOnlyMode) throws IOException { super(connectString, sessionTimeoutMs, watcherManager, allowReadOnlyMode); this.connectString = connectString; this.sessionTimeoutMs = sessionTimeoutMs; this.allowReadOnlyMode = allowReadOnlyMode; this.watcherManager = watcherManager; this.connectRetryPolicy = connectRetryPolicy; this.operationRetryPolicy = operationRetryPolicy; this.rateLimiter = rate > 0 ? RateLimiter.create(rate) : null; this.retryExecutor = Executors.newScheduledThreadPool(retryExecThreadCount, new ThreadFactoryBuilder().setNameFormat("ZKC-retry-executor-%d").build()); this.connectExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("ZKC-connect-executor-%d").build()); // added itself to the watcher watcherManager.addChildWatcher(this); // Stats StatsLogger scopedStatsLogger = statsLogger.scope("zk"); createClientStats = scopedStatsLogger.getOpStatsLogger("create_client"); createStats = scopedStatsLogger.getOpStatsLogger("create"); getStats = scopedStatsLogger.getOpStatsLogger("get_data"); setStats = scopedStatsLogger.getOpStatsLogger("set_data"); deleteStats = scopedStatsLogger.getOpStatsLogger("delete"); getChildrenStats = scopedStatsLogger.getOpStatsLogger("get_children"); existsStats = scopedStatsLogger.getOpStatsLogger("exists"); multiStats = scopedStatsLogger.getOpStatsLogger("multi"); getACLStats = scopedStatsLogger.getOpStatsLogger("get_acl"); setACLStats = scopedStatsLogger.getOpStatsLogger("set_acl"); syncStats = scopedStatsLogger.getOpStatsLogger("sync"); } @Override public void close() throws InterruptedException { closed.set(true); connectExecutor.shutdown(); retryExecutor.shutdown(); closeZkHandle(); } private void closeZkHandle() throws InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { super.close(); } else { zkHandle.close(); } } public void waitForConnection() throws KeeperException, InterruptedException { watcherManager.waitForConnection(); } protected ZooKeeper createZooKeeper() throws IOException { return new ZooKeeper(connectString, sessionTimeoutMs, watcherManager, allowReadOnlyMode); } @Override public void process(WatchedEvent event) { if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) { onExpired(); } } private void onExpired() { if (closed.get()) { // we don't schedule any tries if the client is closed. return; } logger.info("ZooKeeper session {} is expired from {}.", Long.toHexString(getSessionId()), connectString); try { connectExecutor.submit(clientCreator); } catch (RejectedExecutionException ree) { if (!closed.get()) { logger.error("ZooKeeper reconnect task is rejected : ", ree); } } catch (Exception t) { logger.error("Failed to submit zookeeper reconnect task due to runtime exception : ", t); } } /** * A runnable that retries zookeeper operations. */ abstract static class ZkRetryRunnable implements Runnable { final ZooWorker worker; final RateLimiter rateLimiter; final Runnable that; ZkRetryRunnable(RetryPolicy retryPolicy, RateLimiter rateLimiter, OpStatsLogger statsLogger) { this.worker = new ZooWorker(retryPolicy, statsLogger); this.rateLimiter = rateLimiter; that = this; } @Override public void run() { if (null != rateLimiter) { rateLimiter.acquire(); } zkRun(); } abstract void zkRun(); } // inherits from ZooKeeper client for all operations @Override public long getSessionId() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return super.getSessionId(); } return zkHandle.getSessionId(); } @Override public byte[] getSessionPasswd() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return super.getSessionPasswd(); } return zkHandle.getSessionPasswd(); } @Override public int getSessionTimeout() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return super.getSessionTimeout(); } return zkHandle.getSessionTimeout(); } @Override public void addAuthInfo(String scheme, byte[] auth) { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { super.addAuthInfo(scheme, auth); return; } zkHandle.addAuthInfo(scheme, auth); } private void backOffAndRetry(Runnable r, long nextRetryWaitTimeMs) { try { retryExecutor.schedule(r, nextRetryWaitTimeMs, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException ree) { if (!closed.get()) { logger.error("ZooKeeper Operation {} is rejected : ", r, ree); } } } private boolean allowRetry(ZooWorker worker, int rc) { return worker.allowRetry(rc) && !closed.get(); } @Override public synchronized void register(Watcher watcher) { watcherManager.addChildWatcher(watcher); } @Override public List<OpResult> multi(final Iterable<Op> ops) throws InterruptedException, KeeperException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<OpResult>>() { @Override public String toString() { return "multi"; } @Override public List<OpResult> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.multi(ops); } return zkHandle.multi(ops); } }, operationRetryPolicy, rateLimiter, multiStats); } @Override public void multi(final Iterable<Op> ops, final MultiCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, createStats) { final MultiCallback multiCb = new MultiCallback() { @Override public void processResult(int rc, String path, Object ctx, List<OpResult> results) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, results); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.multi(ops, multiCb, worker); } else { zkHandle.multi(ops, multiCb, worker); } } @Override public String toString() { return "multi"; } }; // execute it immediately proc.run(); } @Override @Deprecated public Transaction transaction() { // since there is no reference about which client that the transaction could use // so just use ZooKeeper instance directly. // you'd better to use {@link #multi}. ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return super.transaction(); } return zkHandle.transaction(); } @Override public List<ACL> getACL(final String path, final Stat stat) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<ACL>>() { @Override public String toString() { return String.format("getACL (%s, stat = %s)", path, stat); } @Override public List<ACL> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.getACL(path, stat); } return zkHandle.getACL(path, stat); } }, operationRetryPolicy, rateLimiter, getACLStats); } @Override public void getACL(final String path, final Stat stat, final ACLCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getACLStats) { final ACLCallback aclCb = new ACLCallback() { @Override public void processResult(int rc, String path, Object ctx, List<ACL> acl, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, acl, stat); } } }; @Override public String toString() { return String.format("getACL (%s, stat = %s)", path, stat); } @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.getACL(path, stat, aclCb, worker); } else { zkHandle.getACL(path, stat, aclCb, worker); } } }; // execute it immediately proc.run(); } @Override public Stat setACL(final String path, final List<ACL> acl, final int version) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<Stat>() { @Override public String toString() { return String.format("setACL (%s, acl = %s, version = %d)", path, acl, version); } @Override public Stat call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.setACL(path, acl, version); } return zkHandle.setACL(path, acl, version); } }, operationRetryPolicy, rateLimiter, setACLStats); } @Override public void setACL(final String path, final List<ACL> acl, final int version, final StatCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, setACLStats) { final StatCallback stCb = new StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, stat); } } }; @Override public String toString() { return String.format("setACL (%s, acl = %s, version = %d)", path, acl, version); } @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.setACL(path, acl, version, stCb, worker); } else { zkHandle.setACL(path, acl, version, stCb, worker); } } }; // execute it immediately proc.run(); } @Override public void sync(final String path, final VoidCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, syncStats) { final VoidCallback vCb = new VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context); } } }; @Override public String toString() { return String.format("sync (%s)", path); } @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.sync(path, vCb, worker); } else { zkHandle.sync(path, vCb, worker); } } }; // execute it immediately proc.run(); } @Override public States getState() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.getState(); } else { return zkHandle.getState(); } } @Override public String toString() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.toString(); } else { return zkHandle.toString(); } } @Override public String create(final String path, final byte[] data, final List<ACL> acl, final CreateMode createMode) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<String>() { @Override public String call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.create(path, data, acl, createMode); } return zkHandle.create(path, data, acl, createMode); } @Override public String toString() { return String.format("create (%s, acl = %s, mode = %s)", path, acl, createMode); } }, operationRetryPolicy, rateLimiter, createStats); } @Override public void create(final String path, final byte[] data, final List<ACL> acl, final CreateMode createMode, final StringCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, createStats) { final StringCallback createCb = new StringCallback() { @Override public void processResult(int rc, String path, Object ctx, String name) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, name); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.create(path, data, acl, createMode, createCb, worker); } else { zkHandle.create(path, data, acl, createMode, createCb, worker); } } @Override public String toString() { return String.format("create (%s, acl = %s, mode = %s)", path, acl, createMode); } }; // execute it immediately proc.run(); } @Override public void delete(final String path, final int version) throws KeeperException, InterruptedException { ZooWorker.syncCallWithRetries(this, new ZooCallable<Void>() { @Override public Void call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.delete(path, version); } else { zkHandle.delete(path, version); } return null; } @Override public String toString() { return String.format("delete (%s, version = %d)", path, version); } }, operationRetryPolicy, rateLimiter, deleteStats); } @Override public void delete(final String path, final int version, final VoidCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, deleteStats) { final VoidCallback deleteCb = new VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.delete(path, version, deleteCb, worker); } else { zkHandle.delete(path, version, deleteCb, worker); } } @Override public String toString() { return String.format("delete (%s, version = %d)", path, version); } }; // execute it immediately proc.run(); } @Override public Stat exists(final String path, final Watcher watcher) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<Stat>() { @Override public Stat call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.exists(path, watcher); } return zkHandle.exists(path, watcher); } @Override public String toString() { return String.format("exists (%s, watcher = %s)", path, watcher); } }, operationRetryPolicy, rateLimiter, existsStats); } @Override public Stat exists(final String path, final boolean watch) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<Stat>() { @Override public Stat call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.exists(path, watch); } return zkHandle.exists(path, watch); } @Override public String toString() { return String.format("exists (%s, watcher = %s)", path, watch); } }, operationRetryPolicy, rateLimiter, existsStats); } @Override public void exists(final String path, final Watcher watcher, final StatCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, existsStats) { final StatCallback stCb = new StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.exists(path, watcher, stCb, worker); } else { zkHandle.exists(path, watcher, stCb, worker); } } @Override public String toString() { return String.format("exists (%s, watcher = %s)", path, watcher); } }; // execute it immediately proc.run(); } @Override public void exists(final String path, final boolean watch, final StatCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, existsStats) { final StatCallback stCb = new StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.exists(path, watch, stCb, worker); } else { zkHandle.exists(path, watch, stCb, worker); } } @Override public String toString() { return String.format("exists (%s, watcher = %s)", path, watch); } }; // execute it immediately proc.run(); } @Override public byte[] getData(final String path, final Watcher watcher, final Stat stat) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<byte[]>() { @Override public byte[] call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.getData(path, watcher, stat); } return zkHandle.getData(path, watcher, stat); } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watcher); } }, operationRetryPolicy, rateLimiter, getStats); } @Override public byte[] getData(final String path, final boolean watch, final Stat stat) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<byte[]>() { @Override public byte[] call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.getData(path, watch, stat); } return zkHandle.getData(path, watch, stat); } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watch); } }, operationRetryPolicy, rateLimiter, getStats); } @Override public void getData(final String path, final Watcher watcher, final DataCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) { final DataCallback dataCb = new DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, data, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.getData(path, watcher, dataCb, worker); } else { zkHandle.getData(path, watcher, dataCb, worker); } } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watcher); } }; // execute it immediately proc.run(); } @Override public void getData(final String path, final boolean watch, final DataCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) { final DataCallback dataCb = new DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, data, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.getData(path, watch, dataCb, worker); } else { zkHandle.getData(path, watch, dataCb, worker); } } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watch); } }; // execute it immediately proc.run(); } @Override public Stat setData(final String path, final byte[] data, final int version) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<Stat>() { @Override public Stat call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.setData(path, data, version); } return zkHandle.setData(path, data, version); } @Override public String toString() { return String.format("setData (%s, version = %d)", path, version); } }, operationRetryPolicy, rateLimiter, setStats); } @Override public void setData(final String path, final byte[] data, final int version, final StatCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, setStats) { final StatCallback stCb = new StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.setData(path, data, version, stCb, worker); } else { zkHandle.setData(path, data, version, stCb, worker); } } @Override public String toString() { return String.format("setData (%s, version = %d)", path, version); } }; // execute it immediately proc.run(); } @Override public List<String> getChildren(final String path, final Watcher watcher, final Stat stat) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<String>>() { @Override public List<String> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.getChildren(path, watcher, stat); } return zkHandle.getChildren(path, watcher, stat); } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watcher); } }, operationRetryPolicy, rateLimiter, getChildrenStats); } @Override public List<String> getChildren(final String path, final boolean watch, final Stat stat) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<String>>() { @Override public List<String> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.getChildren(path, watch, stat); } return zkHandle.getChildren(path, watch, stat); } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watch); } }, operationRetryPolicy, rateLimiter, getChildrenStats); } @Override public void getChildren(final String path, final Watcher watcher, final Children2Callback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) { final Children2Callback childCb = new Children2Callback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, children, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.getChildren(path, watcher, childCb, worker); } else { zkHandle.getChildren(path, watcher, childCb, worker); } } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watcher); } }; // execute it immediately proc.run(); } @Override public void getChildren(final String path, final boolean watch, final Children2Callback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) { final Children2Callback childCb = new Children2Callback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, children, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.getChildren(path, watch, childCb, worker); } else { zkHandle.getChildren(path, watch, childCb, worker); } } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watch); } }; // execute it immediately proc.run(); } @Override public List<String> getChildren(final String path, final Watcher watcher) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<String>>() { @Override public List<String> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.getChildren(path, watcher); } return zkHandle.getChildren(path, watcher); } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watcher); } }, operationRetryPolicy, rateLimiter, getChildrenStats); } @Override public List<String> getChildren(final String path, final boolean watch) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooCallable<List<String>>() { @Override public List<String> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return ZooKeeperClient.super.getChildren(path, watch); } return zkHandle.getChildren(path, watch); } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watch); } }, operationRetryPolicy, rateLimiter, getChildrenStats); } @Override public void getChildren(final String path, final Watcher watcher, final ChildrenCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) { final ChildrenCallback childCb = new ChildrenCallback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, children); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.getChildren(path, watcher, childCb, worker); } else { zkHandle.getChildren(path, watcher, childCb, worker); } } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watcher); } }; // execute it immediately proc.run(); } @Override public void getChildren(final String path, final boolean watch, final ChildrenCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) { final ChildrenCallback childCb = new ChildrenCallback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, children); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.getChildren(path, watch, childCb, worker); } else { zkHandle.getChildren(path, watch, childCb, worker); } } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watch); } }; // execute it immediately proc.run(); } }
258
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/zookeeper/RetryPolicy.java
/* * * 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.bookkeeper.zookeeper; /** * Interface of the policy to use when retrying operations. */ public interface RetryPolicy { /** * Called when retrying an operation failed for some reason. Return true if * another attempt is allowed to make. * * @param retryCount * The number of times retried so far (1 for the first time). * @param elapsedRetryTime * The elapsed time since the operation attempted. (in * milliseconds) * @return true if anther attempt is allowed to make. otherwise, false. */ boolean allowRetry(int retryCount, long elapsedRetryTime); /** * Called before making an attempt to retry a failed operation. Return 0 if * an attempt needs to be made immediately. * * @param retryCount * The number of times retried so far (0 for the first time). * @param elapsedRetryTime * The elapsed time since the operation attempted. (in * milliseconds) * @return the elapsed time that the attempt needs to wait before retrying. * (in milliseconds) */ long nextRetryWaitTime(int retryCount, long elapsedRetryTime); }
259
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/zookeeper/ZooWorker.java
/* * * 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.bookkeeper.zookeeper; import com.google.common.util.concurrent.RateLimiter; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.util.MathUtils; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provide a mechanism to perform an operation on ZooKeeper that is safe on disconnections * and recoverable errors. */ class ZooWorker { private static final Logger logger = LoggerFactory.getLogger(ZooWorker.class); int attempts = 0; long startTimeNanos; long elapsedTimeMs = 0L; final RetryPolicy retryPolicy; final OpStatsLogger statsLogger; ZooWorker(RetryPolicy retryPolicy, OpStatsLogger statsLogger) { this.retryPolicy = retryPolicy; this.statsLogger = statsLogger; this.startTimeNanos = MathUtils.nowInNano(); } public boolean allowRetry(int rc) { elapsedTimeMs = MathUtils.elapsedMSec(startTimeNanos); if (!ZooWorker.isRecoverableException(rc)) { if (KeeperException.Code.OK.intValue() == rc) { statsLogger.registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS); } else { statsLogger.registerFailedEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS); } return false; } ++attempts; return retryPolicy.allowRetry(attempts, elapsedTimeMs); } public long nextRetryWaitTime() { return retryPolicy.nextRetryWaitTime(attempts, elapsedTimeMs); } /** * Check whether the given result code is recoverable by retry. * * @param rc result code * @return true if given result code is recoverable. */ public static boolean isRecoverableException(int rc) { return KeeperException.Code.CONNECTIONLOSS.intValue() == rc || KeeperException.Code.OPERATIONTIMEOUT.intValue() == rc || KeeperException.Code.SESSIONMOVED.intValue() == rc || KeeperException.Code.SESSIONEXPIRED.intValue() == rc; } /** * Check whether the given exception is recoverable by retry. * * @param exception given exception * @return true if given exception is recoverable. */ public static boolean isRecoverableException(KeeperException exception) { return isRecoverableException(exception.code().intValue()); } interface ZooCallable<T> { /** * Be compatible with ZooKeeper interface. * * @return value * @throws InterruptedException * @throws KeeperException */ T call() throws InterruptedException, KeeperException; } /** * Execute a sync zookeeper operation with a given retry policy. * * @param client * ZooKeeper client. * @param proc * Synchronous zookeeper operation wrapped in a {@link Callable}. * @param retryPolicy * Retry policy to execute the synchronous operation. * @param rateLimiter * Rate limiter for zookeeper calls * @param statsLogger * Stats Logger for zookeeper client. * @return result of the zookeeper operation * @throws KeeperException any non-recoverable exception or recoverable exception exhausted all retires. * @throws InterruptedException the operation is interrupted. */ public static<T> T syncCallWithRetries(ZooKeeperClient client, ZooCallable<T> proc, RetryPolicy retryPolicy, RateLimiter rateLimiter, OpStatsLogger statsLogger) throws KeeperException, InterruptedException { T result = null; boolean isDone = false; int attempts = 0; long startTimeNanos = MathUtils.nowInNano(); while (!isDone) { try { if (null != client) { client.waitForConnection(); } logger.debug("Execute {} at {} retry attempt.", proc, attempts); if (null != rateLimiter) { rateLimiter.acquire(); } result = proc.call(); isDone = true; statsLogger.registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS); } catch (KeeperException e) { ++attempts; boolean rethrow = true; long elapsedTime = MathUtils.elapsedMSec(startTimeNanos); if (((null != client && isRecoverableException(e)) || null == client) && retryPolicy.allowRetry(attempts, elapsedTime)) { rethrow = false; } if (rethrow) { statsLogger.registerFailedEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS); logger.debug("Stopped executing {} after {} attempts.", proc, attempts); throw e; } TimeUnit.MILLISECONDS.sleep(retryPolicy.nextRetryWaitTime(attempts, elapsedTime)); } } return result; } }
260
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/zookeeper/ExponentialBackOffWithDeadlinePolicy.java
/* * * 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.bookkeeper.zookeeper; import java.util.Arrays; import java.util.Random; import lombok.extern.slf4j.Slf4j; /** * Backoff time determined based as a multiple of baseBackoffTime. * The multiple value depends on retryCount. * If the retry schedule exceeds the deadline, we schedule a final attempt exactly at the deadline. */ @Slf4j public class ExponentialBackOffWithDeadlinePolicy implements RetryPolicy { static final int [] RETRY_BACKOFF = {0, 1, 2, 3, 5, 5, 5, 10, 10, 10, 20, 40, 100}; public static final int JITTER_PERCENT = 10; private final Random random; private final long baseBackoffTime; private final long deadline; private final int maxRetries; public ExponentialBackOffWithDeadlinePolicy(long baseBackoffTime, long deadline, int maxRetries) { this.baseBackoffTime = baseBackoffTime; this.deadline = deadline; this.maxRetries = maxRetries; this.random = new Random(System.currentTimeMillis()); } @Override public boolean allowRetry(int retryCount, long elapsedRetryTime) { return retryCount <= maxRetries && elapsedRetryTime < deadline; } @Override public long nextRetryWaitTime(int retryCount, long elapsedRetryTime) { int idx = retryCount; if (idx >= RETRY_BACKOFF.length) { idx = RETRY_BACKOFF.length - 1; } long waitTime = (baseBackoffTime * RETRY_BACKOFF[idx]); long jitter = (random.nextInt(JITTER_PERCENT) * waitTime / 100); if (elapsedRetryTime + waitTime + jitter > deadline) { log.warn("Final retry attempt: {}, timeleft: {}, stacktrace: {}", retryCount, (deadline - elapsedRetryTime), Arrays.toString(Thread.currentThread().getStackTrace())); return deadline - elapsedRetryTime; } return waitTime + jitter; } }
261
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/zookeeper/ZooKeeperWatcherBase.java
/* * * 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.bookkeeper.zookeeper; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.stats.Counter; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Watcher for receiving zookeeper server connection events. */ public class ZooKeeperWatcherBase implements Watcher { private static final Logger LOG = LoggerFactory .getLogger(ZooKeeperWatcherBase.class); private final int zkSessionTimeOut; private volatile CountDownLatch clientConnectLatch = new CountDownLatch(1); private final CopyOnWriteArraySet<Watcher> childWatchers = new CopyOnWriteArraySet<Watcher>(); private final StatsLogger statsLogger; private final ConcurrentHashMap<Event.KeeperState, Counter> stateCounters = new ConcurrentHashMap<Event.KeeperState, Counter>(); private final ConcurrentHashMap<EventType, Counter> eventCounters = new ConcurrentHashMap<EventType, Counter>(); public ZooKeeperWatcherBase(int zkSessionTimeOut) { this(zkSessionTimeOut, NullStatsLogger.INSTANCE); } public ZooKeeperWatcherBase(int zkSessionTimeOut, StatsLogger statsLogger) { this(zkSessionTimeOut, new HashSet<Watcher>(), statsLogger); } public ZooKeeperWatcherBase(int zkSessionTimeOut, Set<Watcher> childWatchers, StatsLogger statsLogger) { this.zkSessionTimeOut = zkSessionTimeOut; this.childWatchers.addAll(childWatchers); this.statsLogger = statsLogger; } public ZooKeeperWatcherBase addChildWatcher(Watcher watcher) { this.childWatchers.add(watcher); return this; } public ZooKeeperWatcherBase removeChildWatcher(Watcher watcher) { this.childWatchers.remove(watcher); return this; } private Counter getEventCounter(EventType type) { Counter c = eventCounters.get(type); if (null == c) { Counter newCounter = statsLogger.scope("events").getCounter(type.name()); Counter oldCounter = eventCounters.putIfAbsent(type, newCounter); if (null != oldCounter) { c = oldCounter; } else { c = newCounter; } } return c; } public Counter getStateCounter(Event.KeeperState state) { Counter c = stateCounters.get(state); if (null == c) { Counter newCounter = statsLogger.scope("state").getCounter(state.name()); Counter oldCounter = stateCounters.putIfAbsent(state, newCounter); if (null != oldCounter) { c = oldCounter; } else { c = newCounter; } } return c; } @Override public void process(WatchedEvent event) { // If event type is NONE, this is a connection status change if (event.getType() != EventType.None) { if (LOG.isDebugEnabled()) { LOG.debug("Received event: {}, path: {} from ZooKeeper server", event.getType(), event.getPath()); } getEventCounter(event.getType()).inc(); // notify the child watchers notifyEvent(event); return; } getStateCounter(event.getState()).inc(); if (LOG.isDebugEnabled()) { LOG.debug("Received {} from ZooKeeper server", event.getState()); } // TODO: Needs to handle AuthFailed, SaslAuthenticated events // {@link https://github.com/apache/bookkeeper/issues/284} switch (event.getState()) { case SyncConnected: LOG.info("ZooKeeper client is connected now."); clientConnectLatch.countDown(); break; case Disconnected: LOG.info("ZooKeeper client is disconnected from zookeeper now," + " but it is OK unless we received EXPIRED event."); break; case Expired: clientConnectLatch = new CountDownLatch(1); LOG.error("ZooKeeper client connection to the ZooKeeper server has expired!"); break; default: // do nothing break; } // notify the child watchers notifyEvent(event); } /** * Waiting for the SyncConnected event from the ZooKeeper server. * * @throws KeeperException * when there is no connection * @throws InterruptedException * interrupted while waiting for connection */ public void waitForConnection() throws KeeperException, InterruptedException { if (!clientConnectLatch.await(zkSessionTimeOut, TimeUnit.MILLISECONDS)) { throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS); } } /** * Return zookeeper session time out. */ public int getZkSessionTimeOut() { return zkSessionTimeOut; } /** * Notify Event to child watchers. * * @param event * Watched event received from ZooKeeper. */ private void notifyEvent(WatchedEvent event) { // notify child watchers for (Watcher w : childWatchers) { try { w.process(event); } catch (Exception t) { LOG.warn("Encountered unexpected exception from watcher {} : ", w, t); } } } }
262
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/zookeeper/ExponentialBackoffRetryPolicy.java
/* * * 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.bookkeeper.zookeeper; import java.util.Random; /** * A retry policy implementation that backoff retries exponentially. */ public class ExponentialBackoffRetryPolicy implements RetryPolicy { private final Random random; private final int maxRetries; private final long baseBackoffTime; public ExponentialBackoffRetryPolicy(long baseBackoffTime, int maxRetries) { this.maxRetries = maxRetries; this.baseBackoffTime = baseBackoffTime; this.random = new Random(System.currentTimeMillis()); } @Override public boolean allowRetry(int retryCount, long elapsedRetryTime) { return retryCount <= maxRetries; } @Override public long nextRetryWaitTime(int retryCount, long elapsedRetryTime) { return baseBackoffTime * Math.max(1, random.nextInt(Math.max(1, 1 << (retryCount + 1)))); } }
263
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/zookeeper/package-info.java
/* * 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. */ /** * A simple retryable zookeeper wrapper provided in bookkeeper. */ package org.apache.bookkeeper.zookeeper;
264
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/streaming/LedgerInputStream.java
/* * * 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.bookkeeper.streaming; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Enumeration; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.LedgerEntry; import org.apache.bookkeeper.client.LedgerHandle; /** * An input stream on reading data from a ledger. */ public class LedgerInputStream extends InputStream { private final LedgerHandle lh; private ByteBuffer bytebuff; byte[] bbytes; long lastEntry = 0; int increment = 50; int defaultSize = 1024 * 1024; // 1MB default size Enumeration<LedgerEntry> ledgerSeq = null; /** * construct a outputstream from a ledger handle. * * @param lh * ledger handle * @throws BKException when encountered bookkeeper exceptions * @throws InterruptedException when opening a ledger input stream is interrupted. */ public LedgerInputStream(LedgerHandle lh) throws BKException, InterruptedException { this.lh = lh; bbytes = new byte[defaultSize]; this.bytebuff = ByteBuffer.wrap(bbytes); this.bytebuff.position(this.bytebuff.limit()); lastEntry = Math.min(lh.getLastAddConfirmed(), increment); ledgerSeq = lh.readEntries(0, lastEntry); } /** * construct a outputstream from a ledger handle. * * @param lh * the ledger handle * @param size * the size of the buffer * @throws BKException when encountered bookkeeper exceptions * @throws InterruptedException when opening a ledger input stream is interrupted. */ public LedgerInputStream(LedgerHandle lh, int size) throws BKException, InterruptedException { this.lh = lh; bbytes = new byte[size]; this.bytebuff = ByteBuffer.wrap(bbytes); this.bytebuff.position(this.bytebuff.limit()); lastEntry = Math.min(lh.getLastAddConfirmed(), increment); ledgerSeq = lh.readEntries(0, lastEntry); } /** * Method close currently doesn't do anything. The application * is supposed to open and close the ledger handle backing up * a stream ({@link LedgerHandle}). */ @Override public void close() { // do nothing // let the application // close the ledger } /** * refill the buffer, we need to read more bytes. * * @return if we can refill or not */ private synchronized boolean refill() throws IOException { bytebuff.clear(); if (!ledgerSeq.hasMoreElements() && lastEntry >= lh.getLastAddConfirmed()) { return false; } if (!ledgerSeq.hasMoreElements()) { // do refill long last = Math.min(lastEntry + increment, lh.getLastAddConfirmed()); try { ledgerSeq = lh.readEntries(lastEntry + 1, last); } catch (BKException bk) { IOException ie = new IOException(bk.getMessage()); ie.initCause(bk); throw ie; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } lastEntry = last; } LedgerEntry le = ledgerSeq.nextElement(); bbytes = le.getEntry(); bytebuff = ByteBuffer.wrap(bbytes); return true; } @Override public synchronized int read() throws IOException { boolean toread = true; if (bytebuff.remaining() == 0) { // their are no remaining bytes toread = refill(); } if (toread) { int ret = 0xFF & bytebuff.get(); return ret; } return -1; } @Override public synchronized int read(byte[] b) throws IOException { // be smart ... just copy the bytes // once and return the size // user will call it again boolean toread = true; if (bytebuff.remaining() == 0) { toread = refill(); } if (toread) { int bcopied = bytebuff.remaining(); int tocopy = Math.min(bcopied, b.length); // cannot used gets because of // the underflow/overflow exceptions System.arraycopy(bbytes, bytebuff.position(), b, 0, tocopy); bytebuff.position(bytebuff.position() + tocopy); return tocopy; } return -1; } @Override public synchronized int read(byte[] b, int off, int len) throws IOException { // again dont need ot fully // fill b, just return // what we have and let the application call read // again boolean toread = true; if (bytebuff.remaining() == 0) { toread = refill(); } if (toread) { int bcopied = bytebuff.remaining(); int tocopy = Math.min(bcopied, len); System.arraycopy(bbytes, bytebuff.position(), b, off, tocopy); bytebuff.position(bytebuff.position() + tocopy); return tocopy; } return -1; } }
265
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/streaming/LedgerOutputStream.java
/* * * 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.bookkeeper.streaming; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.LedgerHandle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * this class provides a streaming api to get an output stream from a ledger * handle and write to it as a stream of bytes. This is built on top of * ledgerhandle api and uses a buffer to cache the data written to it and writes * out the entry to the ledger. */ public class LedgerOutputStream extends OutputStream { private static final Logger LOG = LoggerFactory.getLogger(LedgerOutputStream.class); private final LedgerHandle lh; private ByteBuffer bytebuff; byte[] bbytes; int defaultSize = 1024 * 1024; // 1MB default size /** * construct a outputstream from a ledger handle. * * @param lh * ledger handle */ public LedgerOutputStream(LedgerHandle lh) { this.lh = lh; bbytes = new byte[defaultSize]; this.bytebuff = ByteBuffer.wrap(bbytes); } /** * construct a outputstream from a ledger handle. * * @param lh * the ledger handle * @param size * the size of the buffer */ public LedgerOutputStream(LedgerHandle lh, int size) { this.lh = lh; bbytes = new byte[size]; this.bytebuff = ByteBuffer.wrap(bbytes); } @Override public void close() { // flush everything // we have flush(); } @Override public synchronized void flush() { // lets flush all the data // into the ledger entry if (bytebuff.position() > 0) { // copy the bytes into // a new byte buffer and send it out byte[] b = new byte[bytebuff.position()]; LOG.info("Comment: flushing with params " + " " + bytebuff.position()); System.arraycopy(bbytes, 0, b, 0, bytebuff.position()); try { lh.addEntry(b); } catch (InterruptedException ie) { LOG.warn("Interrupted while flusing " + ie); Thread.currentThread().interrupt(); } catch (BKException bke) { LOG.warn("BookKeeper exception ", bke); } } } /** * make space for len bytes to be written to the buffer. * * @param len * @return if true then we can make space for len if false we cannot */ private boolean makeSpace(int len) { if (bytebuff.remaining() < len) { flush(); bytebuff.clear(); return bytebuff.capacity() >= len; } return true; } @Override public synchronized void write(byte[] b) { if (makeSpace(b.length)) { bytebuff.put(b); } else { try { lh.addEntry(b); } catch (InterruptedException ie) { LOG.warn("Interrupted while writing", ie); Thread.currentThread().interrupt(); } catch (BKException bke) { LOG.warn("BookKeeper exception", bke); } } } @Override public synchronized void write(byte[] b, int off, int len) { if (!makeSpace(len)) { // lets try making the buffer bigger bbytes = new byte[len]; bytebuff = ByteBuffer.wrap(bbytes); } bytebuff.put(b, off, len); } @Override public synchronized void write(int b) throws IOException { makeSpace(1); byte oneB = (byte) (b & 0xFF); bytebuff.put(oneB); } }
266
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/streaming/package-info.java
/* * 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. */ /** * A java io stream wrapper over bookkeeper ledgers. */ package org.apache.bookkeeper.streaming;
267
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tls/SecurityHandlerFactory.java
/* * 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.bookkeeper.tls; import io.netty.buffer.ByteBufAllocator; import io.netty.handler.ssl.SslHandler; import org.apache.bookkeeper.conf.AbstractConfiguration; /** * A factory to manage the security handlers. */ public interface SecurityHandlerFactory { /** * The security handler type. */ enum NodeType { Unknown, Client, Server, } String getHandlerName(); void init(NodeType type, AbstractConfiguration conf, ByteBufAllocator allocator) throws SecurityException; SslHandler newTLSHandler(); default SslHandler newTLSHandler(String host, int port) { return this.newTLSHandler(); } }
268
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tls/SecurityException.java
/* * 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.bookkeeper.tls; /** * Signals that a security-related exception has occurred. */ public class SecurityException extends Exception { public SecurityException() {} public SecurityException(String message) { super(message); } public SecurityException(Throwable cause) { super(cause); } public SecurityException(String message, Throwable cause) { super(message, cause); } }
269
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tls/FileModifiedTimeUpdater.java
/* * 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.bookkeeper.tls; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileTime; import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Holder class to validate file modification. */ public class FileModifiedTimeUpdater { @Getter String fileName; @Getter FileTime lastModifiedTime; public FileModifiedTimeUpdater(String fileName) { this.fileName = fileName; this.lastModifiedTime = updateLastModifiedTime(); } private FileTime updateLastModifiedTime() { if (fileName != null) { Path p = Paths.get(fileName); try { return Files.getLastModifiedTime(p); } catch (IOException e) { LOG.error("Unable to fetch lastModified time for file {}: ", fileName, e); } } return null; } public boolean checkAndRefresh() { FileTime newLastModifiedTime = updateLastModifiedTime(); if (newLastModifiedTime != null && !newLastModifiedTime.equals(lastModifiedTime)) { this.lastModifiedTime = newLastModifiedTime; return true; } return false; } private static final Logger LOG = LoggerFactory.getLogger(FileModifiedTimeUpdater.class); }
270
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tls/BookieAuthZFactory.java
/* * 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.bookkeeper.tls; import com.google.common.base.Strings; import java.io.IOException; import java.security.cert.X509Certificate; import java.util.Collection; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.auth.AuthCallbacks; import org.apache.bookkeeper.auth.AuthToken; import org.apache.bookkeeper.auth.BookKeeperPrincipal; import org.apache.bookkeeper.auth.BookieAuthProvider; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.proto.BookieConnectionPeer; import org.apache.bookkeeper.util.CertUtils; /** * Authorization factory class. */ @Slf4j public class BookieAuthZFactory implements BookieAuthProvider.Factory { public String[] allowedRoles; @Override public String getPluginName() { return "BookieAuthZFactory"; } @Override public void init(ServerConfiguration conf) throws IOException { // Read from config allowedRoles = conf.getAuthorizedRoles(); if (allowedRoles == null || allowedRoles.length == 0) { throw new RuntimeException("Configuration option \'bookieAuthProviderFactoryClass\' is set to" + " \'BookieAuthZFactory\' but no roles set for configuration field \'authorizedRoles\'."); } // If authorization is enabled and there are no roles, exit for (String allowedRole : allowedRoles) { if (Strings.isNullOrEmpty(allowedRole)) { throw new RuntimeException("Configuration option \'bookieAuthProviderFactoryClass\' is set to" + " \'BookieAuthZFactory\' but no roles set for configuration field \'authorizedRoles\'."); } } } @Override public BookieAuthProvider newProvider(BookieConnectionPeer addr, final AuthCallbacks.GenericCallback<Void> completeCb) { return new BookieAuthProvider() { AuthCallbacks.GenericCallback<Void> completeCallback = completeCb; @Override public void onProtocolUpgrade() { try { boolean secureBookieSideChannel = addr.isSecure(); Collection<Object> certificates = addr.getProtocolPrincipals(); if (secureBookieSideChannel && !certificates.isEmpty() && certificates.iterator().next() instanceof X509Certificate) { X509Certificate tempCert = (X509Certificate) certificates.iterator().next(); String[] certRole = CertUtils.getRolesFromOU(tempCert); if (certRole == null || certRole.length == 0) { log.error("AuthZ failed: No cert role in OU field of certificate. Must have a role from " + "allowedRoles list {} host: {}", allowedRoles, addr.getRemoteAddr()); completeCallback.operationComplete(BKException.Code.UnauthorizedAccessException, null); return; } boolean authorized = false; for (String allowedRole : allowedRoles) { if (certRole[0].equals(allowedRole)) { authorized = true; break; } } if (authorized) { addr.setAuthorizedId(new BookKeeperPrincipal(certRole[0])); completeCallback.operationComplete(BKException.Code.OK, null); } else { log.error("AuthZ failed: Cert role {} doesn't match allowedRoles list {}; host: {}", certRole, allowedRoles, addr.getRemoteAddr()); completeCallback.operationComplete(BKException.Code.UnauthorizedAccessException, null); } } else { if (!secureBookieSideChannel) { log.error("AuthZ failed: Bookie side channel is not secured; host: {}", addr.getRemoteAddr()); } else if (certificates.isEmpty()) { log.error("AuthZ failed: Certificate missing; host: {}", addr.getRemoteAddr()); } else { log.error("AuthZ failed: Certs are missing or not X509 type; host: {}", addr.getRemoteAddr()); } completeCallback.operationComplete(BKException.Code.UnauthorizedAccessException, null); } } catch (Exception e) { log.error("AuthZ failed: Failed to parse certificate; host: {}, {}", addr.getRemoteAddr(), e); completeCallback.operationComplete(BKException.Code.UnauthorizedAccessException, null); } } @Override public void process(AuthToken m, AuthCallbacks.GenericCallback<AuthToken> cb) { } }; } }
271
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tls/TLSContextFactory.java
/* * 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.bookkeeper.tls; import com.google.common.base.Strings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.buffer.ByteBufAllocator; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslProvider; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.Security; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLParameters; import javax.net.ssl.TrustManagerFactory; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.conf.AbstractConfiguration; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.commons.io.FileUtils; /** * A factory to manage TLS contexts. */ @Slf4j public class TLSContextFactory implements SecurityHandlerFactory { public static final Provider BC_PROVIDER = getProvider(); public static final String BC_FIPS_PROVIDER_CLASS = "org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider"; public static final String BC_NON_FIPS_PROVIDER_CLASS = "org.bouncycastle.jce.provider.BouncyCastleProvider"; // Security.getProvider("BC") / Security.getProvider("BCFIPS"). // also used to get Factories. e.g. CertificateFactory.getInstance("X.509", "BCFIPS") public static final String BC_FIPS = "BCFIPS"; public static final String BC = "BC"; /** * Get Bouncy Castle provider, and call Security.addProvider(provider) if success. */ public static Provider getProvider() { boolean isProviderInstalled = Security.getProvider(BC) != null || Security.getProvider(BC_FIPS) != null; if (isProviderInstalled) { Provider provider = Security.getProvider(BC) != null ? Security.getProvider(BC) : Security.getProvider(BC_FIPS); if (log.isDebugEnabled()) { log.debug("Already instantiated Bouncy Castle provider {}", provider.getName()); } return provider; } // Not installed, try load from class path try { return getBCProviderFromClassPath(); } catch (Exception e) { log.warn("Not able to get Bouncy Castle provider for both FIPS and Non-FIPS from class path:", e); throw new RuntimeException(e); } } /** * Get Bouncy Castle provider from classpath, and call Security.addProvider. * Throw Exception if failed. */ public static Provider getBCProviderFromClassPath() throws Exception { Class clazz; try { clazz = Class.forName(BC_FIPS_PROVIDER_CLASS); } catch (ClassNotFoundException cnf) { if (log.isDebugEnabled()) { log.debug("Not able to get Bouncy Castle provider: {}, try to get FIPS provider {}", BC_NON_FIPS_PROVIDER_CLASS, BC_FIPS_PROVIDER_CLASS); } // attempt to use the NON_FIPS provider. clazz = Class.forName(BC_NON_FIPS_PROVIDER_CLASS); } @SuppressWarnings("unchecked") Provider provider = (Provider) clazz.getDeclaredConstructor().newInstance(); Security.addProvider(provider); if (log.isDebugEnabled()) { log.debug("Found and Instantiated Bouncy Castle provider in classpath {}", provider.getName()); } return provider; } /** * Supported Key File Types. */ public enum KeyStoreType { PKCS12("PKCS12"), JKS("JKS"), PEM("PEM"); private String str; KeyStoreType(String str) { this.str = str; } @Override public String toString() { return this.str; } } private static final String TLSCONTEXT_HANDLER_NAME = "tls"; private NodeType type; private String[] protocols; private String[] ciphers; private volatile SslContext sslContext; private ByteBufAllocator allocator; private AbstractConfiguration config; private FileModifiedTimeUpdater tlsCertificateFilePath, tlsKeyStoreFilePath, tlsKeyStorePasswordFilePath, tlsTrustStoreFilePath, tlsTrustStorePasswordFilePath; private long certRefreshTime; private volatile long certLastRefreshTime; private boolean isServerCtx; private String getPasswordFromFile(String path) throws IOException { byte[] pwd; File passwdFile = new File(path); if (passwdFile.length() == 0) { return ""; } pwd = FileUtils.readFileToByteArray(passwdFile); return new String(pwd, StandardCharsets.UTF_8); } @SuppressFBWarnings( value = "OBL_UNSATISFIED_OBLIGATION", justification = "work around for java 9: https://github.com/spotbugs/spotbugs/issues/493") private KeyStore loadKeyStore(String keyStoreType, String keyStoreLocation, String keyStorePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore ks = KeyStore.getInstance(keyStoreType); try (FileInputStream ksin = new FileInputStream(keyStoreLocation)) { ks.load(ksin, keyStorePassword.trim().toCharArray()); } return ks; } @Override public String getHandlerName() { return TLSCONTEXT_HANDLER_NAME; } private KeyManagerFactory initKeyManagerFactory(String keyStoreType, String keyStoreLocation, String keyStorePasswordPath) throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, InvalidKeySpecException { KeyManagerFactory kmf = null; if (Strings.isNullOrEmpty(keyStoreLocation)) { log.error("Key store location cannot be empty when Mutual Authentication is enabled!"); throw new SecurityException("Key store location cannot be empty when Mutual Authentication is enabled!"); } String keyStorePassword = ""; if (!Strings.isNullOrEmpty(keyStorePasswordPath)) { keyStorePassword = getPasswordFromFile(keyStorePasswordPath); } // Initialize key file KeyStore ks = loadKeyStore(keyStoreType, keyStoreLocation, keyStorePassword); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keyStorePassword.trim().toCharArray()); return kmf; } private TrustManagerFactory initTrustManagerFactory(String trustStoreType, String trustStoreLocation, String trustStorePasswordPath) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, SecurityException { TrustManagerFactory tmf; if (Strings.isNullOrEmpty(trustStoreLocation)) { log.error("Trust Store location cannot be empty!"); throw new SecurityException("Trust Store location cannot be empty!"); } String trustStorePassword = ""; if (!Strings.isNullOrEmpty(trustStorePasswordPath)) { trustStorePassword = getPasswordFromFile(trustStorePasswordPath); } // Initialize trust file KeyStore ts = loadKeyStore(trustStoreType, trustStoreLocation, trustStorePassword); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); return tmf; } private SslProvider getTLSProvider(String sslProvider) { if (sslProvider.trim().equalsIgnoreCase("OpenSSL")) { if (OpenSsl.isAvailable()) { log.info("Security provider - OpenSSL"); return SslProvider.OPENSSL; } Throwable causeUnavailable = OpenSsl.unavailabilityCause(); log.warn("OpenSSL Unavailable: ", causeUnavailable); log.info("Security provider - JDK"); return SslProvider.JDK; } log.info("Security provider - JDK"); return SslProvider.JDK; } private void createClientContext() throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, InvalidKeySpecException, NoSuchProviderException { ClientConfiguration clientConf = (ClientConfiguration) config; markAutoCertRefresh(clientConf.getTLSCertificatePath(), clientConf.getTLSKeyStore(), clientConf.getTLSKeyStorePasswordPath(), clientConf.getTLSTrustStore(), clientConf.getTLSTrustStorePasswordPath()); updateClientContext(); } private synchronized void updateClientContext() throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, InvalidKeySpecException, NoSuchProviderException { final SslContextBuilder sslContextBuilder; final ClientConfiguration clientConf; final SslProvider provider; final boolean clientAuthentication; // get key-file and trust-file locations and passwords if (!(config instanceof ClientConfiguration)) { throw new SecurityException("Client configruation not provided"); } clientConf = (ClientConfiguration) config; provider = getTLSProvider(clientConf.getTLSProvider()); clientAuthentication = clientConf.getTLSClientAuthentication(); switch (KeyStoreType.valueOf(clientConf.getTLSTrustStoreType())) { case PEM: if (Strings.isNullOrEmpty(clientConf.getTLSTrustStore())) { throw new SecurityException("CA Certificate required"); } sslContextBuilder = SslContextBuilder.forClient() .trustManager(new File(clientConf.getTLSTrustStore())) .ciphers(null) .sessionCacheSize(0) .sessionTimeout(0) .sslProvider(provider) .clientAuth(ClientAuth.REQUIRE); break; case JKS: // falling thru, same as PKCS12 case PKCS12: TrustManagerFactory tmf = initTrustManagerFactory(clientConf.getTLSTrustStoreType(), clientConf.getTLSTrustStore(), clientConf.getTLSTrustStorePasswordPath()); sslContextBuilder = SslContextBuilder.forClient() .trustManager(tmf) .ciphers(null) .sessionCacheSize(0) .sessionTimeout(0) .sslProvider(provider) .clientAuth(ClientAuth.REQUIRE); break; default: throw new SecurityException("Invalid Truststore type: " + clientConf.getTLSTrustStoreType()); } if (clientAuthentication) { switch (KeyStoreType.valueOf(clientConf.getTLSKeyStoreType())) { case PEM: final String keyPassword; if (Strings.isNullOrEmpty(clientConf.getTLSCertificatePath())) { throw new SecurityException("Valid Certificate is missing"); } if (Strings.isNullOrEmpty(clientConf.getTLSKeyStore())) { throw new SecurityException("Valid Key is missing"); } if (!Strings.isNullOrEmpty(clientConf.getTLSKeyStorePasswordPath())) { keyPassword = getPasswordFromFile(clientConf.getTLSKeyStorePasswordPath()); } else { keyPassword = null; } sslContextBuilder.keyManager(new File(clientConf.getTLSCertificatePath()), new File(clientConf.getTLSKeyStore()), keyPassword); break; case JKS: // falling thru, same as PKCS12 case PKCS12: KeyManagerFactory kmf = initKeyManagerFactory(clientConf.getTLSKeyStoreType(), clientConf.getTLSKeyStore(), clientConf.getTLSKeyStorePasswordPath()); sslContextBuilder.keyManager(kmf); break; default: throw new SecurityException("Invalid Keyfile type" + clientConf.getTLSKeyStoreType()); } } sslContext = sslContextBuilder.build(); certLastRefreshTime = System.currentTimeMillis(); } private void createServerContext() throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, InvalidKeySpecException, IllegalArgumentException { isServerCtx = true; ServerConfiguration clientConf = (ServerConfiguration) config; markAutoCertRefresh(clientConf.getTLSCertificatePath(), clientConf.getTLSKeyStore(), clientConf.getTLSKeyStorePasswordPath(), clientConf.getTLSTrustStore(), clientConf.getTLSTrustStorePasswordPath()); updateServerContext(); } private synchronized SslContext getSSLContext() { long now = System.currentTimeMillis(); if ((certRefreshTime > 0 && now > (certLastRefreshTime + certRefreshTime))) { if (tlsCertificateFilePath.checkAndRefresh() || tlsKeyStoreFilePath.checkAndRefresh() || tlsKeyStorePasswordFilePath.checkAndRefresh() || tlsTrustStoreFilePath.checkAndRefresh() || tlsTrustStorePasswordFilePath.checkAndRefresh()) { try { log.info("Updating tls certs certFile={}, keyStoreFile={}, trustStoreFile={}", tlsCertificateFilePath.getFileName(), tlsKeyStoreFilePath.getFileName(), tlsTrustStoreFilePath.getFileName()); if (isServerCtx) { updateServerContext(); } else { updateClientContext(); } } catch (Exception e) { log.info("Failed to refresh tls certs", e); } } } return sslContext; } private synchronized void updateServerContext() throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, InvalidKeySpecException, IllegalArgumentException { final SslContextBuilder sslContextBuilder; final ServerConfiguration serverConf; final SslProvider provider; final boolean clientAuthentication; // get key-file and trust-file locations and passwords if (!(config instanceof ServerConfiguration)) { throw new SecurityException("Server configruation not provided"); } serverConf = (ServerConfiguration) config; provider = getTLSProvider(serverConf.getTLSProvider()); clientAuthentication = serverConf.getTLSClientAuthentication(); switch (KeyStoreType.valueOf(serverConf.getTLSKeyStoreType())) { case PEM: final String keyPassword; if (Strings.isNullOrEmpty(serverConf.getTLSKeyStore())) { throw new SecurityException("Key path is required"); } if (Strings.isNullOrEmpty(serverConf.getTLSCertificatePath())) { throw new SecurityException("Certificate path is required"); } if (!Strings.isNullOrEmpty(serverConf.getTLSKeyStorePasswordPath())) { keyPassword = getPasswordFromFile(serverConf.getTLSKeyStorePasswordPath()); } else { keyPassword = null; } sslContextBuilder = SslContextBuilder .forServer(new File(serverConf.getTLSCertificatePath()), new File(serverConf.getTLSKeyStore()), keyPassword) .ciphers(null) .sessionCacheSize(0) .sessionTimeout(0) .sslProvider(provider) .startTls(true); break; case JKS: // falling thru, same as PKCS12 case PKCS12: KeyManagerFactory kmf = initKeyManagerFactory(serverConf.getTLSKeyStoreType(), serverConf.getTLSKeyStore(), serverConf.getTLSKeyStorePasswordPath()); sslContextBuilder = SslContextBuilder.forServer(kmf) .ciphers(null) .sessionCacheSize(0) .sessionTimeout(0) .sslProvider(provider) .startTls(true); break; default: throw new SecurityException("Invalid Keyfile type" + serverConf.getTLSKeyStoreType()); } if (clientAuthentication) { sslContextBuilder.clientAuth(ClientAuth.REQUIRE); switch (KeyStoreType.valueOf(serverConf.getTLSTrustStoreType())) { case PEM: if (Strings.isNullOrEmpty(serverConf.getTLSTrustStore())) { throw new SecurityException("CA Certificate chain is required"); } sslContextBuilder.trustManager(new File(serverConf.getTLSTrustStore())); break; case JKS: // falling thru, same as PKCS12 case PKCS12: TrustManagerFactory tmf = initTrustManagerFactory(serverConf.getTLSTrustStoreType(), serverConf.getTLSTrustStore(), serverConf.getTLSTrustStorePasswordPath()); sslContextBuilder.trustManager(tmf); break; default: throw new SecurityException("Invalid Truststore type" + serverConf.getTLSTrustStoreType()); } } sslContext = sslContextBuilder.build(); certLastRefreshTime = System.currentTimeMillis(); } @Override public synchronized void init(NodeType type, AbstractConfiguration conf, ByteBufAllocator allocator) throws SecurityException { this.allocator = allocator; this.config = conf; this.type = type; final String enabledProtocols; final String enabledCiphers; certRefreshTime = TimeUnit.SECONDS.toMillis(conf.getTLSCertFilesRefreshDurationSeconds()); enabledCiphers = conf.getTLSEnabledCipherSuites(); enabledProtocols = conf.getTLSEnabledProtocols(); try { switch (type) { case Client: createClientContext(); break; case Server: createServerContext(); break; default: throw new SecurityException(new IllegalArgumentException("Invalid NodeType")); } if (enabledProtocols != null && !enabledProtocols.isEmpty()) { protocols = enabledProtocols.split(","); } if (enabledCiphers != null && !enabledCiphers.isEmpty()) { ciphers = enabledCiphers.split(","); } } catch (KeyStoreException e) { throw new RuntimeException("Standard keystore type missing", e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Standard algorithm missing", e); } catch (CertificateException e) { throw new SecurityException("Unable to load keystore", e); } catch (IOException e) { throw new SecurityException("Error initializing SSLContext", e); } catch (UnrecoverableKeyException e) { throw new SecurityException("Unable to load key manager, possibly bad password", e); } catch (InvalidKeySpecException e) { throw new SecurityException("Unable to load key manager", e); } catch (IllegalArgumentException e) { throw new SecurityException("Invalid TLS configuration", e); } catch (NoSuchProviderException e) { throw new SecurityException("No such provider", e); } } @Override public SslHandler newTLSHandler() { return this.newTLSHandler(null, -1); } @Override public SslHandler newTLSHandler(String peer, int port) { SslHandler sslHandler = getSSLContext().newHandler(allocator, peer, port); if (protocols != null && protocols.length != 0) { sslHandler.engine().setEnabledProtocols(protocols); } if (log.isDebugEnabled()) { log.debug("Enabled cipher protocols: {} ", Arrays.toString(sslHandler.engine().getEnabledProtocols())); } if (ciphers != null && ciphers.length != 0) { sslHandler.engine().setEnabledCipherSuites(ciphers); } if (log.isDebugEnabled()) { log.debug("Enabled cipher suites: {} ", Arrays.toString(sslHandler.engine().getEnabledCipherSuites())); } if (type == NodeType.Client && ((ClientConfiguration) config).getHostnameVerificationEnabled()) { SSLParameters sslParameters = sslHandler.engine().getSSLParameters(); sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); sslHandler.engine().setSSLParameters(sslParameters); if (log.isDebugEnabled()) { log.debug("Enabled endpointIdentificationAlgorithm: HTTPS"); } } return sslHandler; } private void markAutoCertRefresh(String tlsCertificatePath, String tlsKeyStore, String tlsKeyStorePasswordPath, String tlsTrustStore, String tlsTrustStorePasswordPath) { tlsCertificateFilePath = new FileModifiedTimeUpdater(tlsCertificatePath); tlsKeyStoreFilePath = new FileModifiedTimeUpdater(tlsKeyStore); tlsKeyStorePasswordFilePath = new FileModifiedTimeUpdater(tlsKeyStorePasswordPath); tlsTrustStoreFilePath = new FileModifiedTimeUpdater(tlsTrustStore); tlsTrustStorePasswordFilePath = new FileModifiedTimeUpdater(tlsTrustStorePasswordPath); } }
272
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tls/SecurityProviderFactoryFactory.java
/* * 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.bookkeeper.tls; import org.apache.bookkeeper.common.util.ReflectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A factory to manage security provider factories. */ public abstract class SecurityProviderFactoryFactory { private static final Logger LOG = LoggerFactory.getLogger(SecurityProviderFactoryFactory.class); public static SecurityHandlerFactory getSecurityProviderFactory(String securityHandler) throws SecurityException { if ((securityHandler == null) || (securityHandler.equals(""))) { return null; } SecurityHandlerFactory shFactory; try { Class<? extends SecurityHandlerFactory> shFactoryClass = ReflectionUtils.forName(securityHandler, SecurityHandlerFactory.class); shFactory = ReflectionUtils.newInstance(shFactoryClass); LOG.info("Loaded security handler for {}", securityHandler); } catch (RuntimeException re) { LOG.error("Unable to load security handler for {}: ", securityHandler, re.getCause()); throw new SecurityException(re.getCause()); } return shFactory; } }
273
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tls/package-info.java
/* * 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. */ /** * Security and TLS-related classes. */ package org.apache.bookkeeper.tls;
274
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/shims
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/shims/zk/ZooKeeperServerShim.java
/* * * 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.bookkeeper.shims.zk; import java.io.File; import java.io.IOException; /** * In order to be compatible with multiple versions of ZooKeeper. * All parts of the ZooKeeper Server that are not cross-version * compatible are encapsulated in an implementation of this class. */ public interface ZooKeeperServerShim { /** * Initialize zookeeper server. * * @param snapDir * Snapshot Dir. * @param logDir * Log Dir. * @param zkPort * ZooKeeper Port. * @param maxCC * Max Concurrency for Client. * @throws IOException when failed to initialize zookeeper server. */ void initialize(File snapDir, File logDir, int zkPort, int maxCC) throws IOException; /** * Start the zookeeper server. * * @throws IOException when failed to start zookeeper server. */ void start() throws IOException; /** * Stop the zookeeper server. */ void stop(); }
275
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/shims
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/shims/zk/ZooKeeperServerShimImpl.java
/* * * 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.bookkeeper.shims.zk; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.zookeeper.server.NIOServerCnxnFactory; import org.apache.zookeeper.server.ZooKeeperServer; class ZooKeeperServerShimImpl implements ZooKeeperServerShim { ZooKeeperServer zks = null; NIOServerCnxnFactory serverFactory = null; @Override public void initialize(File snapDir, File logDir, int zkPort, int maxCC) throws IOException { zks = new ZooKeeperServer(snapDir, logDir, ZooKeeperServer.DEFAULT_TICK_TIME); serverFactory = new NIOServerCnxnFactory(); serverFactory.configure(new InetSocketAddress(zkPort), maxCC); } @Override public void start() throws IOException { if (null == zks || null == serverFactory) { throw new IOException("Start zookeeper server before initialization."); } try { serverFactory.startup(zks); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted when starting zookeeper server : ", e); } } @Override public void stop() { if (null != serverFactory) { serverFactory.shutdown(); } if (null != zks) { zks.shutdown(); } } }
276
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/shims
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/shims/zk/ZooKeeperServerShimFactory.java
/* * * 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.bookkeeper.shims.zk; import java.io.File; import java.io.IOException; /** * A factory to create zookeeper server. */ public class ZooKeeperServerShimFactory { public static ZooKeeperServerShim createServer(File snapDir, File logDir, int zkPort, int maxCC) throws IOException { ZooKeeperServerShim server = new ZooKeeperServerShimImpl(); server.initialize(snapDir, logDir, zkPort, maxCC); return server; } }
277
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/shims
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/shims/zk/package-info.java
/* * 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. */ /** * A shim layer to adopt different zookeeper versions. */ package org.apache.bookkeeper.shims.zk;
278
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/verifier/DirectBookkeeperDriver.java
/* * * 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.bookkeeper.verifier; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.LedgerHandle; /** * Driver for a normal Bookkeeper cluster. */ class DirectBookkeeperDriver implements BookkeeperVerifier.BookkeeperDriver { private final ConcurrentHashMap<Long, LedgerHandle> openHandles = new ConcurrentHashMap<>(); private BookKeeper client; DirectBookkeeperDriver(BookKeeper client) { this.client = client; } @Override public void createLedger(long ledgerID, int enSize, int writeQSize, int ackQSize, Consumer<Integer> cb) { client.asyncCreateLedgerAdv( ledgerID, enSize, writeQSize, ackQSize, BookKeeper.DigestType.CRC32, new byte[0], (rc, lh, ctx) -> { openHandles.put(ledgerID, lh); cb.accept(rc); }, null, null); } @Override public void closeLedger(long ledgerID, Consumer<Integer> cb) { LedgerHandle handle = openHandles.remove(ledgerID); handle.asyncClose( (rc, lh, ctx) -> cb.accept(rc), null); } @Override public void deleteLedger(long ledgerID, Consumer<Integer> cb) { client.asyncDeleteLedger(ledgerID, (rc, ctx) -> { cb.accept(rc); }, null); } @Override public void writeEntry(long ledgerID, long entryID, byte[] data, Consumer<Integer> cb) { LedgerHandle handle; handle = openHandles.get(ledgerID); if (handle == null) { cb.accept(BKException.Code.WriteException); return; } handle.asyncAddEntry(entryID, data, (rc, lh, entryId, ctx) -> { cb.accept(rc); }, null); } @Override public void readEntries( long ledgerID, long firstEntryID, long lastEntryID, BiConsumer<Integer, ArrayList<byte[]>> cb) { client.asyncOpenLedgerNoRecovery(ledgerID, BookKeeper.DigestType.CRC32, new byte[0], (rc, lh, ctx) -> { if (rc != 0) { cb.accept(rc, null); return; } System.out.format("Got handle for read %d -> %d on ledger %d%n", firstEntryID, lastEntryID, ledgerID); lh.asyncReadEntries(firstEntryID, lastEntryID, (rc1, lh1, seq, ctx1) -> { System.out.format("Read cb %d -> %d on ledger %d%n", firstEntryID, lastEntryID, ledgerID); ArrayList<byte[]> results = new ArrayList<>(); if (rc1 == 0) { while (seq.hasMoreElements()) { results.add(seq.nextElement().getEntry()); } System.out.format("About to close handle for read %d -> %d on ledger %d%n", firstEntryID, lastEntryID, ledgerID); } lh.asyncClose((rc2, lh2, ctx2) -> { System.out.format("Closed handle for read %d -> %d on ledger %d result %d%n", firstEntryID, lastEntryID, ledgerID, rc2); cb.accept(rc1 == 0 ? rc2 : rc1, results); }, null); }, null); }, null); } }
279
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/verifier/BookkeeperVerifier.java
/* * 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.bookkeeper.verifier; import static com.google.common.base.Preconditions.checkState; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.apache.bookkeeper.client.BKException; /** * Encapsulates logic for playing and verifying operations against a bookkeeper-like * interface. The test state consists of a set of ledgers in 1 of several states: * 1) opening -- waiting for driver to complete open * 2) open -- valid targets for reads and writes * 3) live -- valid targets for reads * 4) deleting * Each ledger moves in sequence through these states. See startWrite for the * code driving the lifecycle. */ public class BookkeeperVerifier { private final Queue<Exception> errors = new LinkedList<>(); private synchronized boolean checkReturn(long ledgerID, int rc) { if (BKException.Code.OK != rc) { String error = String.format("Got error %d on ledger %d", rc, ledgerID); System.out.println(error); propagateExceptionToMain(BKException.create(rc)); return true; } else { return false; } } private synchronized void propagateExceptionToMain(Exception e) { errors.add(e); this.notifyAll(); } private synchronized void printThrowExceptions() throws Exception { if (!errors.isEmpty()) { for (Exception e: errors) { System.out.format("Error found: %s%n", e.toString()); e.printStackTrace(); } throw errors.poll(); } } /** * Provides an interface for translating test operations into operations on a * cluster. */ public interface BookkeeperDriver { void createLedger( long ledgerID, int enSize, int writeQSize, int ackQSize, Consumer<Integer> cb ); void closeLedger( long ledgerID, Consumer<Integer> cb ); void deleteLedger( long ledgerID, Consumer<Integer> cb ); void writeEntry( long ledgerID, long entryID, byte[] data, Consumer<Integer> cb ); /** * Callback for reads. */ interface ReadCallback { void complete( long ledgerID, ArrayList<byte[]> results ); } void readEntries( long ledgerID, long firstEntryID, long lastEntryID, BiConsumer<Integer, ArrayList<byte[]>> cb); } private final BookkeeperDriver driver; private final int ensembleSize; private final int writeQuorum; private final int ackQuorum; private final int duration; private final int drainTimeout; private final int targetConcurrentLedgers; private final int targetConcurrentWrites; private final int targetWriteGroup; private final int targetReadGroup; private final int targetLedgers; private final int targetEntrySize; private final int targetConcurrentReads; private final double coldToHotRatio; private final long targetLedgerEntries; BookkeeperVerifier( BookkeeperDriver driver, int ensembleSize, int writeQuorum, int ackQuorum, int duration, int drainTimeout, int targetConcurrentLedgers, int targetConcurrentWrites, int targetWriteGroup, int targetReadGroup, int targetLedgers, long targetLedgerSize, int targetEntrySize, int targetConcurrentReads, double coldToHotRatio) { this.driver = driver; this.ensembleSize = ensembleSize; this.writeQuorum = writeQuorum; this.ackQuorum = ackQuorum; this.duration = duration; this.drainTimeout = drainTimeout; this.targetConcurrentLedgers = targetConcurrentLedgers; this.targetConcurrentWrites = targetConcurrentWrites; this.targetWriteGroup = targetWriteGroup; this.targetReadGroup = targetReadGroup; this.targetLedgers = targetLedgers; this.targetEntrySize = targetEntrySize; this.targetConcurrentReads = targetConcurrentReads; this.coldToHotRatio = coldToHotRatio; this.targetLedgerEntries = targetLedgerSize / targetEntrySize; } private int outstandingWriteCount = 0; private int outstandingReadCount = 0; private long nextLedger = 0; private long getNextLedgerID() { return nextLedger++; } /** * State required to regenerate an entry. */ @SuppressFBWarnings("DMI_RANDOM_USED_ONLY_ONCE") class EntryInfo { private final long entryID; private final long seed; EntryInfo(long entryID, long seed) { this.entryID = entryID; this.seed = seed; } byte[] getBuffer() { Random rand = new Random(seed); byte[] ret = new byte[targetEntrySize]; rand.nextBytes(ret); return ret; } long getEntryID() { return entryID; } } /** * Contains the state required to reconstruct the contents of any entry in the ledger. * The seed value passed into the constructor fully determines the contents of the * ledger. Each EntryInfo has its own seed generated sequentially from a Random instance * seeded from the original seed. It then uses that seed to generate a secondary Random * instance for generating the bytes within the entry. See EntryIterator for details. * Random(seed) * | * E0 -> Random(E0) -> getBuffer() * | * E1 -> Random(E1) -> getBuffer() * | * E2 -> Random(E2) -> getBuffer() * | * E3 -> Random(E3) -> getBuffer() * | * E4 -> Random(E4) -> getBuffer() * | * ... */ class LedgerInfo { private final long ledgerID; private final long seed; private long lastEntryIDCompleted = -1; private long confirmedLAC = -1; private boolean closed = false; final TreeSet<Long> writesInProgress = new TreeSet<>(); final TreeSet<Long> writesCompleted = new TreeSet<>(); int readsInProgress = 0; Consumer<Consumer<Integer>> onLastOp = null; Consumer<Consumer<Integer>> onLastWrite = null; EntryIterator iter; LedgerInfo(long ledgerID, long seed) { this.ledgerID = ledgerID; this.seed = seed; iter = new EntryIterator(); } long getLastEntryIDCompleted() { return lastEntryIDCompleted; } long getConfirmedLAC() { return confirmedLAC; } ArrayList<EntryInfo> getNextEntries(int num) { ArrayList<EntryInfo> ret = new ArrayList<>(); for (int i = 0; i < num && iter.hasNext(); ++i) { ret.add(iter.next()); } return ret; } class EntryIterator implements Iterator<EntryInfo> { Random rand; long currentID; long currentSeed; EntryIterator() { seek(-1); } void seek(long entryID) { currentID = -1; currentSeed = seed; rand = new Random(seed); while (currentID < entryID) { advance(); } } void advance() { currentSeed = rand.nextLong(); currentID++; } EntryInfo get() { return new EntryInfo(currentID, currentSeed); } @Override public boolean hasNext() { return currentID < targetLedgerEntries; } @Override public EntryInfo next() { advance(); return get(); } } EntryIterator getIterator() { return new EntryIterator(); } void openWrite(long entryID) { writesInProgress.add(entryID); System.out.format("Open writes, %s%n", writesInProgress); } void incReads() { readsInProgress++; System.out.format("Inc reads to %d%n", readsInProgress); } /** * The idea here is that we may need to register an operation which needs to run * whenever the final op completes on this Ledger (like deletion). If there * are none, newOnLastOp should be called synchronously with cb. Otherwise, * cb should be called synchronously with cb and newOnLastOp should be called * with the cb passed in with the decReads or closeWrite. * In the deletion case, cb would be the callback for the error from * the deletion operation (if it happens). The reason for all of this is that * the delete case will need to chain an async call to delete into the async callback * chain for whatever the last operation to complete on this Ledger. newOnLastOp * would invoke that delete. The cb passed in allows it to pick up and continue * the original chain. * @param cb Callback to get result of newOnLastOp if called now * @param newOnLastOp Callback to be invoked on the last decReads or closeWrite, * should be passed the cb passed in with the final closeWrite * or decReads */ void onLastOpComplete( Consumer<Integer> cb, Consumer<Consumer<Integer>> newOnLastOp) { checkState(onLastOp == null); onLastOp = newOnLastOp; checkOpComplete(cb); } /** * Very similar to onLastOpComplete, but gets called on the final call to closeWrite. * @param cb Callback to get result of newOnLastWrite if called now * @param newOnLastWrite Callback to be invoked on the last closeWrite, * should be passed the cb passed in with the final closeWrite. */ void onLastWriteComplete( Consumer<Integer> cb, Consumer<Consumer<Integer>> newOnLastWrite) { assert (onLastWrite == null); onLastWrite = newOnLastWrite; checkWriteComplete(cb); } void closeWrite(long entryID, Consumer<Integer> cb) { writesInProgress.remove(entryID); writesCompleted.add(entryID); long completedTo = writesInProgress.isEmpty() ? Long.MAX_VALUE : writesInProgress.first(); while (!writesCompleted.isEmpty() && writesCompleted.first() < completedTo) { lastEntryIDCompleted = writesCompleted.first(); writesCompleted.remove(writesCompleted.first()); } checkWriteComplete((rc) -> { checkReturn(ledgerID, rc); checkOpComplete(cb); }); } void updateLAC(long lac) { if (lac > confirmedLAC) { confirmedLAC = lac; } } void decReads(Consumer<Integer> cb) { --readsInProgress; checkOpComplete(cb); } private void checkWriteComplete(Consumer<Integer> cb) { if (writesInProgress.isEmpty() && onLastWrite != null) { System.out.format("checkWriteComplete: done%n"); onLastWrite.accept(cb); onLastWrite = null; } else { System.out.format( "checkWriteComplete: ledger %d, writesInProgress %s%n", ledgerID, writesInProgress); cb.accept(0); } } private void checkOpComplete(Consumer<Integer> cb) { if (readsInProgress == 0 && writesInProgress.isEmpty() && onLastOp != null) { System.out.format("checkOpComplete: done%n"); onLastOp.accept(cb); onLastOp = null; } else { System.out.format( "checkOpComplete: ledger %d, writesInProgress %s, readsInProgress %d%n", ledgerID, writesInProgress, readsInProgress); cb.accept(0); } } public boolean isClosed() { return closed; } public void setClosed() { closed = true; confirmedLAC = lastEntryIDCompleted; } } private final Set<LedgerInfo> openingLedgers = new HashSet<>(); private final Set<LedgerInfo> openLedgers = new HashSet<>(); private final Set<LedgerInfo> liveLedgers = new HashSet<>(); private final Random opRand = new Random(); private LedgerInfo getRandomLedger(Collection<LedgerInfo> ledgerCollection) { int elem = opRand.nextInt(ledgerCollection.size()); Iterator<LedgerInfo> iter = ledgerCollection.iterator(); for (int i = 0; i < elem; ++i) { iter.next(); } return iter.next(); } private synchronized boolean startRead() { if (outstandingReadCount > targetConcurrentReads) { System.out.format("Not starting another read, enough in progress%n"); /* Caller should exit and wait for outstandingReadCount to fall */ return false; } LedgerInfo ledger; if (!openLedgers.isEmpty() && (opRand.nextDouble() > coldToHotRatio)) { ledger = getRandomLedger(openLedgers); System.out.format("Reading from open ledger %d%n", ledger.ledgerID); } else if (!liveLedgers.isEmpty()) { ledger = getRandomLedger(liveLedgers); System.out.format("Reading from cold ledger %d%n", ledger.ledgerID); } else { /* No readable ledgers, either startWrite can make progress, or there are already ledgers * opening. */ return false; } long lastEntryCompleted = ledger.getConfirmedLAC(); if (lastEntryCompleted <= 0) { System.out.format("No readable entries in ledger %d, let's wait%n", ledger.ledgerID); /* Either startWrite can make progress or there are already a bunch in progress */ return false; } long start = Math.abs(opRand.nextLong() % lastEntryCompleted); long end = start + targetReadGroup > lastEntryCompleted ? lastEntryCompleted : start + targetReadGroup; System.out.format("Reading %d -> %d from ledger %d%n", start, end, ledger.ledgerID); LedgerInfo finalLedger = ledger; ledger.incReads(); driver.readEntries(ledger.ledgerID, start, end, (rc, results) -> { synchronized (BookkeeperVerifier.this) { if (checkReturn(ledger.ledgerID, rc)) { return; } System.out.format("Read %d -> %d from ledger %d complete%n", start, end, ledger.ledgerID); long current = start; LedgerInfo.EntryIterator iterator = finalLedger.getIterator(); iterator.seek(current - 1); for (byte[] result : results) { byte[] check = iterator.next().getBuffer(); if (result.length != check.length) { propagateExceptionToMain(new Exception(String.format( "Mismatched entry length on entry %d for ledger %d, read returned %d, should be %d", current, ledger.ledgerID, result.length, check.length) )); } /* Verify contents */ if (!Arrays.equals(check, result)) { int i = 0; for (; i < check.length; ++i) { if (check[i] != result[i]) { break; } } propagateExceptionToMain(new Exception(String.format( "Mismatched entry contents on entry %d for ledger %d at offset %d, length %d", current, ledger.ledgerID, i, check.length) )); } current++; } finalLedger.decReads((rc2) -> { synchronized (BookkeeperVerifier.this) { checkReturn(ledger.ledgerID, rc2); System.out.format("Read %d -> %d from ledger %d releasing read%n", start, end, ledger.ledgerID); outstandingReadCount--; BookkeeperVerifier.this.notifyAll(); } }); } }); ++outstandingReadCount; return true; } class WriteCallback implements Consumer<Integer> { private int completed = 0; private final int toWaitFor; private final LedgerInfo ledger; private final long lastEntry; private final long pendingLAC; WriteCallback(LedgerInfo ledger, long lastEntry, long pendingLAC, int toWaitFor) { this.toWaitFor = toWaitFor; this.ledger = ledger; this.lastEntry = lastEntry; this.pendingLAC = pendingLAC; } @Override public void accept(Integer rc) { synchronized (BookkeeperVerifier.this) { if (checkReturn(ledger.ledgerID, rc)) { return; } ++completed; if (toWaitFor == completed) { System.out.format("Writes ending at %d complete on ledger %d%n", lastEntry, ledger.ledgerID); ledger.closeWrite(lastEntry, (rc2) -> { synchronized (BookkeeperVerifier.this) { checkReturn(ledger.ledgerID, rc2); System.out.format("Writes ending at %d complete on ledger %d releasing write%n", lastEntry, ledger.ledgerID); --outstandingWriteCount; BookkeeperVerifier.this.notifyAll(); } }); ledger.updateLAC(pendingLAC); } } } } /** * Attempt to start one more write, return false if too many are in progress. * @return false if unable to start more */ private synchronized boolean startWrite() { if (outstandingWriteCount > targetConcurrentWrites) { System.out.format("Write paused, too many outstanding writes%n"); /* Caller should release lock and wait for outstandingWriteCount to fall */ return false; } if (openLedgers.size() + openingLedgers.size() < targetConcurrentLedgers) { /* Not enough open ledgers, open a new one -- counts as a write */ long newID = getNextLedgerID(); System.out.format("Creating new ledger %d%n", newID); LedgerInfo ledger = new LedgerInfo(newID, opRand.nextLong()); openingLedgers.add(ledger); driver.createLedger(newID, ensembleSize, writeQuorum, ackQuorum, (rc) -> { synchronized (BookkeeperVerifier.this) { checkReturn(newID, rc); System.out.format("Created new ledger %d%n", newID); openingLedgers.remove(ledger); openLedgers.add(ledger); --outstandingWriteCount; BookkeeperVerifier.this.notifyAll(); } }); ++outstandingWriteCount; return true; } else if (openLedgers.isEmpty()) { System.out.format("Not starting a write, no open ledgers, already opening the limit%n"); /* Caller should release lock and wait for openLedgers to be populated */ return false; } else { LedgerInfo ledger = getRandomLedger(openLedgers); ArrayList<EntryInfo> toWrite = ledger.getNextEntries(targetWriteGroup); long lastEntry = toWrite.get(toWrite.size() - 1).getEntryID(); System.out.format( "Writing entries %d -> %d to ledger %d%n", toWrite.get(0).getEntryID(), lastEntry, ledger.ledgerID); ledger.openWrite(lastEntry); WriteCallback writeCB = new WriteCallback( ledger, lastEntry, ledger.getLastEntryIDCompleted(), toWrite.size()); for (EntryInfo entry: toWrite) { driver.writeEntry(ledger.ledgerID, entry.getEntryID(), entry.getBuffer(), writeCB); } ++outstandingWriteCount; if (lastEntry >= targetLedgerEntries) { /* Remove this ledger from the writable list, mark for closing once all open writes complete */ System.out.format("Marking ledger %d for close%n", ledger.ledgerID); openLedgers.remove(ledger); liveLedgers.add(ledger); ledger.onLastWriteComplete((rc) -> checkReturn(ledger.ledgerID, rc), (Consumer<Integer> cb) -> { System.out.format("Closing ledger %d%n", ledger.ledgerID); driver.closeLedger(ledger.ledgerID, (Integer rc) -> { synchronized (BookkeeperVerifier.this) { ledger.setClosed(); System.out.format("Closed ledger %d%n", ledger.ledgerID); if (liveLedgers.size() >= targetLedgers) { /* We've closed the ledger, but now we have too many closed but readable ledgers, * start deleting one. */ LedgerInfo toDelete = getRandomLedger(liveLedgers); final long ledgerID = toDelete.ledgerID; System.out.format("Marking ledger %d for deletion%n", ledgerID); liveLedgers.remove(toDelete); toDelete.onLastOpComplete(cb, (Consumer<Integer> cb2) -> { System.out.format("Deleting ledger %d%n", ledgerID); driver.deleteLedger(ledgerID, (rc2) -> { synchronized (BookkeeperVerifier.this) { System.out.format("Deleted ledger %d%n", ledgerID); cb2.accept(rc2); } }); }); } else { cb.accept(rc); } } }); }); } Collections.shuffle(toWrite); return true; } } /** * This is the method used to invoke the main loop of the IO driver. run() will loop * starting IO requests until the time runs out on the test and all outstanding requests * complete. Test execution state is accessed only under the instance lock for 'this'. * There is no fine grained locking, hence run() simply needs to be synchronized and * can wait for IOs to complete atomically with startWrite and startRead returning * false (see those comments). * * @throws Exception */ public synchronized void run() throws Exception { long start = System.currentTimeMillis(); long testEnd = start + (duration * 1000); long testDrainEnd = testEnd + (drainTimeout * 1000); /* Keep IO running until testEnd */ while (System.currentTimeMillis() < testEnd) { /* see startRead and startWrite, they return false once no more IO can be started */ while (startRead() || startWrite()) {} long toWait = testEnd - System.currentTimeMillis(); /* atomically wait for either IO to complete or the test to end */ this.wait(toWait < 0 ? 0 : toWait); printThrowExceptions(); } /* Wait for all in progress ops to complete, outstanding*Count is updated under the lock */ while ((System.currentTimeMillis() < testDrainEnd) && (outstandingReadCount > 0 || outstandingWriteCount > 0)) { System.out.format("reads: %d, writes: %d%n", outstandingReadCount, outstandingWriteCount); System.out.format("openingLedgers:%n"); for (LedgerInfo li: openingLedgers) { System.out.format( "Ledger %d has reads: %d, writes: %d%n", li.ledgerID, li.readsInProgress, li.writesInProgress.size()); } System.out.format("openLedgers:%n"); for (LedgerInfo li: openLedgers) { System.out.format( "Ledger %d has reads: %d, writes: %d%n", li.ledgerID, li.readsInProgress, li.writesInProgress.size()); } System.out.format("liveLedgers:%n"); for (LedgerInfo li: liveLedgers) { System.out.format( "Ledger %d has reads: %d, writes: %d%n", li.ledgerID, li.readsInProgress, li.writesInProgress.size()); } long toWait = testDrainEnd - System.currentTimeMillis(); this.wait(toWait < 0 ? 0 : toWait); printThrowExceptions(); } if (outstandingReadCount > 0 || outstandingWriteCount > 0) { throw new Exception("Failed to drain ops before timeout%n"); } } }
280
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/verifier/BookkeeperVerifierMain.java
/* * * 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.bookkeeper.verifier; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; /** * Performs a configurable IO stream against a bookkeeper client while * validating results. */ public class BookkeeperVerifierMain { private static void printHelpAndExit(Options options, String header, int code) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "BookkeeperVerifierMain", header, options, "", true); System.exit(code); } public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption( "ledger_path", true, "Hostname or IP of bookie to benchmark"); options.addOption( "zookeeper", true, "Zookeeper ensemble, (default \"localhost:2181\")"); options.addOption( "ensemble_size", true, "Bookkeeper client ensemble size"); options.addOption( "write_quorum", true, "Bookkeeper client write quorum size"); options.addOption("ack_quorum", true, "Bookkeeper client ack quorum size"); options.addOption("duration", true, "Run duration in seconds"); options.addOption("drain_timeout", true, "Seconds to wait for in progress ops to end"); options.addOption( "target_concurrent_ledgers", true, "target number ledgers to write to concurrently"); options.addOption( "target_concurrent_writes", true, "target number of concurrent writes per ledger"); options.addOption( "target_write_group", true, "target number of entries to write at a time"); options.addOption( "target_read_group", true, "target number of entries to read at a time"); options.addOption("target_ledgers", true, "Target number of ledgers"); options.addOption("target_ledger_size", true, "Target size per ledger"); options.addOption("target_entry_size", true, "Target size per entry"); options.addOption( "target_concurrent_reads", true, "Number of reads to maintain"); options.addOption( "cold_to_hot_ratio", true, "Ratio of reads on open ledgers"); options.addOption("help", false, "Print this help message"); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { printHelpAndExit(options, "Unable to parse command line", 1); } if (cmd.hasOption("help")) { printHelpAndExit(options, "Help:", 0); } String ledgerPath = cmd.getOptionValue("ledger_path", "/ledgers"); String zkString = cmd.getOptionValue("zookeeper", "localhost:2181"); int ensembleSize = 0; int writeQuorum = 0; int ackQuorum = 0; int duration = 0; int drainTimeout = 0; int targetConcurrentLedgers = 0; int targetConcurrentWrites = 0; int targetWriteGroup = 0; int targetReadGroup = 0; int targetLedgers = 0; long targetLedgerSize = 0; int targetEntrySize = 0; int targetConcurrentReads = 0; double coldToHotRatio = 0; try { ensembleSize = Integer.parseInt(cmd.getOptionValue("ensemble_size", "3")); writeQuorum = Integer.parseInt(cmd.getOptionValue("write_quorum", "3")); ackQuorum = Integer.parseInt(cmd.getOptionValue("ack_quorum", "2")); duration = Integer.parseInt(cmd.getOptionValue("duration", "600")); drainTimeout = Integer.parseInt(cmd.getOptionValue("drain_timeout", "10")); targetConcurrentLedgers = Integer.parseInt(cmd.getOptionValue("target_concurrent_ledgers", "4")); targetConcurrentWrites = Integer.parseInt(cmd.getOptionValue("target_concurrent_writes", "12")); targetWriteGroup = Integer.parseInt(cmd.getOptionValue("target_write_group", "4")); targetReadGroup = Integer.parseInt(cmd.getOptionValue("target_read_group", "4")); targetLedgers = Integer.parseInt(cmd.getOptionValue("target_ledgers", "32")); targetLedgerSize = Long.parseLong(cmd.getOptionValue( "target_ledger_size", "33554432")); targetEntrySize = Integer.parseInt(cmd.getOptionValue( "target_entry_size", "16384")); targetConcurrentReads = Integer.parseInt(cmd.getOptionValue( "target_concurrent_reads", "16")); coldToHotRatio = Double.parseDouble( cmd.getOptionValue("cold_to_hot_ratio", "0.5")); } catch (NumberFormatException e) { printHelpAndExit(options, "Invalid argument", 0); } ClientConfiguration conf = new ClientConfiguration(); conf.setMetadataServiceUri("zk://" + zkString + ledgerPath); BookKeeper bkclient = new BookKeeper(conf); BookkeeperVerifier verifier = new BookkeeperVerifier( new DirectBookkeeperDriver(bkclient), ensembleSize, writeQuorum, ackQuorum, duration, drainTimeout, targetConcurrentLedgers, targetConcurrentWrites, targetWriteGroup, targetReadGroup, targetLedgers, targetLedgerSize, targetEntrySize, targetConcurrentReads, coldToHotRatio); try { verifier.run(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { bkclient.close(); } } }
281
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/verifier/package-info.java
/* * 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. */ /** * Simple self-verifying workload generator. */ package org.apache.bookkeeper.verifier;
282
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/AuditorBookieCheckTask.java
/** * 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.bookkeeper.replication; import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.commons.collections4.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AuditorBookieCheckTask extends AuditorTask { private static final Logger LOG = LoggerFactory.getLogger(AuditorBookieCheckTask.class); private final BookieLedgerIndexer bookieLedgerIndexer; private final BiConsumer<Void, Throwable> submitCheckTask; public AuditorBookieCheckTask(ServerConfiguration conf, AuditorStats auditorStats, BookKeeperAdmin admin, LedgerManager ledgerManager, LedgerUnderreplicationManager ledgerUnderreplicationManager, ShutdownTaskHandler shutdownTaskHandler, BookieLedgerIndexer bookieLedgerIndexer, BiConsumer<AtomicBoolean, Throwable> hasAuditCheckTask, BiConsumer<Void, Throwable> submitCheckTask) { super(conf, auditorStats, admin, ledgerManager, ledgerUnderreplicationManager, shutdownTaskHandler, hasAuditCheckTask); this.bookieLedgerIndexer = bookieLedgerIndexer; this.submitCheckTask = submitCheckTask; } @Override protected void runTask() { if (!hasBookieCheckTask()) { startAudit(true); } else { // if due to a lost bookie an audit task was scheduled, // let us not run this periodic bookie check now, if we // went ahead, we'll report under replication and the user // wanted to avoid that(with lostBookieRecoveryDelay option) LOG.info("Audit already scheduled; skipping periodic bookie check"); auditorStats.getNumSkippingCheckTaskTimes().inc(); } } @Override public void shutdown() { } /** * Start running the actual audit task. * * @param shutDownTask A boolean that indicates whether or not to schedule shutdown task on any failure */ void startAudit(boolean shutDownTask) { try { auditBookies(); shutDownTask = false; } catch (BKException bke) { LOG.error("Exception getting bookie list", bke); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.error("Interrupted while watching available bookies ", ie); } catch (ReplicationException.BKAuditException bke) { LOG.error("Exception while watching available bookies", bke); } if (shutDownTask) { submitShutdownTask(); } } void auditBookies() throws ReplicationException.BKAuditException, InterruptedException, BKException { try { waitIfLedgerReplicationDisabled(); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); return; } catch (ReplicationException.UnavailableException ue) { LOG.error("Underreplication unavailable, skipping audit." + "Will retry after a period"); return; } LOG.info("Starting auditBookies"); Stopwatch stopwatch = Stopwatch.createStarted(); // put exit cases here Map<String, Set<Long>> ledgerDetails = generateBookie2LedgersIndex(); try { if (!isLedgerReplicationEnabled()) { // has been disabled while we were generating the index // discard this run, and schedule a new one submitCheckTask.accept(null, null); return; } } catch (ReplicationException.UnavailableException ue) { LOG.error("Underreplication unavailable, skipping audit." + "Will retry after a period"); return; } List<String> availableBookies = getAvailableBookies(); // find lost bookies Set<String> knownBookies = ledgerDetails.keySet(); Collection<String> lostBookies = CollectionUtils.subtract(knownBookies, availableBookies); auditorStats.getBookieToLedgersMapCreationTime() .registerSuccessfulEvent(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); if (lostBookies.size() > 0) { try { FutureUtils.result( handleLostBookiesAsync(lostBookies, ledgerDetails), ReplicationException.EXCEPTION_HANDLER); } catch (ReplicationException e) { throw new ReplicationException.BKAuditException(e.getMessage(), e.getCause()); } auditorStats.getURLPublishTimeForLostBookies() .registerSuccessfulEvent(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); } LOG.info("Completed auditBookies"); auditorStats.getAuditBookiesTime().registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); } private Map<String, Set<Long>> generateBookie2LedgersIndex() throws ReplicationException.BKAuditException { return bookieLedgerIndexer.getBookieToLedgerIndex(); } private CompletableFuture<?> handleLostBookiesAsync(Collection<String> lostBookies, Map<String, Set<Long>> ledgerDetails) { LOG.info("Following are the failed bookies: {}," + " and searching its ledgers for re-replication", lostBookies); return FutureUtils.processList( Lists.newArrayList(lostBookies), bookieIP -> publishSuspectedLedgersAsync( Lists.newArrayList(bookieIP), ledgerDetails.get(bookieIP)), null ); } protected void waitIfLedgerReplicationDisabled() throws ReplicationException.UnavailableException, InterruptedException { if (!isLedgerReplicationEnabled()) { LOG.info("LedgerReplication is disabled externally through Zookeeper, " + "since DISABLE_NODE ZNode is created, so waiting untill it is enabled"); ReplicationEnableCb cb = new ReplicationEnableCb(); ledgerUnderreplicationManager.notifyLedgerReplicationEnabled(cb); cb.await(); } } }
283
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/BookieLedgerIndexer.java
/* * 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.bookkeeper.replication; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.Processor; import org.apache.bookkeeper.replication.ReplicationException.BKAuditException; import org.apache.zookeeper.AsyncCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Preparing bookie vs its corresponding ledgers. This will always look up the * ledgermanager for ledger metadata and will generate indexes. */ public class BookieLedgerIndexer { private static final Logger LOG = LoggerFactory.getLogger(BookieLedgerIndexer.class); private final LedgerManager ledgerManager; public BookieLedgerIndexer(LedgerManager ledgerManager) { this.ledgerManager = ledgerManager; } /** * Generating bookie vs its ledgers map by reading all the ledgers in each * bookie and parsing its metadata. * * @return bookie2ledgersMap map of bookie vs ledgers * @throws BKAuditException * exception while getting bookie-ledgers */ public Map<String, Set<Long>> getBookieToLedgerIndex() throws BKAuditException { // bookie vs ledgers map final ConcurrentHashMap<String, Set<Long>> bookie2ledgersMap = new ConcurrentHashMap<String, Set<Long>>(); final CountDownLatch ledgerCollectorLatch = new CountDownLatch(1); Processor<Long> ledgerProcessor = new Processor<Long>() { @Override public void process(Long ledgerId, AsyncCallback.VoidCallback iterCallback) { ledgerManager.readLedgerMetadata(ledgerId).whenComplete((metadata, exception) -> { if (exception == null) { for (Map.Entry<Long, ? extends List<BookieId>> ensemble : metadata.getValue().getAllEnsembles().entrySet()) { for (BookieId bookie : ensemble.getValue()) { putLedger(bookie2ledgersMap, bookie.toString(), ledgerId); } } iterCallback.processResult(BKException.Code.OK, null, null); } else if (BKException.getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsOnMetadataServerException) { LOG.info("Ignoring replication of already deleted ledger {}", ledgerId); iterCallback.processResult(BKException.Code.OK, null, null); } else { LOG.warn("Unable to read the ledger: {} information", ledgerId); iterCallback.processResult(BKException.getExceptionCode(exception), null, null); } }); } }; // Reading the result after processing all the ledgers final List<Integer> resultCode = new ArrayList<Integer>(1); ledgerManager.asyncProcessLedgers(ledgerProcessor, new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String s, Object obj) { resultCode.add(rc); ledgerCollectorLatch.countDown(); } }, null, BKException.Code.OK, BKException.Code.ReadException); try { ledgerCollectorLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new BKAuditException( "Exception while getting the bookie-ledgers", e); } if (!resultCode.contains(BKException.Code.OK)) { throw new BKAuditException( "Exception while getting the bookie-ledgers", BKException .create(resultCode.get(0))); } return bookie2ledgersMap; } private void putLedger(ConcurrentHashMap<String, Set<Long>> bookie2ledgersMap, String bookie, long ledgerId) { Set<Long> ledgers = bookie2ledgersMap.get(bookie); // creates an empty list and add to bookie for keeping its ledgers if (ledgers == null) { ledgers = Collections.synchronizedSet(new HashSet<Long>()); Set<Long> oldLedgers = bookie2ledgersMap.putIfAbsent(bookie, ledgers); if (oldLedgers != null) { ledgers = oldLedgers; } } ledgers.add(ledgerId); } }
284
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/AutoRecoveryMain.java
/* * * 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.bookkeeper.replication; import static org.apache.bookkeeper.replication.ReplicationStats.AUDITOR_SCOPE; import static org.apache.bookkeeper.replication.ReplicationStats.REPLICATION_WORKER_SCOPE; import com.google.common.annotations.VisibleForTesting; import java.io.File; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.net.MalformedURLException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.apache.bookkeeper.bookie.BookieCriticalThread; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.ExitCode; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.BookKeeperClientStats; import org.apache.bookkeeper.common.component.ComponentStarter; import org.apache.bookkeeper.common.component.LifecycleComponent; import org.apache.bookkeeper.common.component.LifecycleComponentStack; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.MetadataClientDriver; import org.apache.bookkeeper.replication.ReplicationException.CompatibilityException; import org.apache.bookkeeper.replication.ReplicationException.UnavailableException; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.bookkeeper.server.http.BKHttpServiceProvider; import org.apache.bookkeeper.server.service.AutoRecoveryService; import org.apache.bookkeeper.server.service.HttpService; import org.apache.bookkeeper.server.service.StatsProviderService; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.configuration.ConfigurationException; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class to start/stop the AutoRecovery daemons Auditor and ReplicationWorker. * * <p>TODO: eliminate the direct usage of zookeeper here {@link https://github.com/apache/bookkeeper/issues/1332} */ public class AutoRecoveryMain { private static final Logger LOG = LoggerFactory .getLogger(AutoRecoveryMain.class); private final ServerConfiguration conf; final BookKeeper bkc; final AuditorElector auditorElector; final ReplicationWorker replicationWorker; final AutoRecoveryDeathWatcher deathWatcher; int exitCode; private volatile boolean shuttingDown = false; private volatile boolean running = false; // Exception handler private volatile UncaughtExceptionHandler uncaughtExceptionHandler = null; public AutoRecoveryMain(ServerConfiguration conf) throws IOException, InterruptedException, KeeperException, UnavailableException, CompatibilityException { this(conf, NullStatsLogger.INSTANCE); } public AutoRecoveryMain(ServerConfiguration conf, StatsLogger statsLogger) throws IOException, InterruptedException, KeeperException, UnavailableException, CompatibilityException { this.conf = conf; this.bkc = Auditor.createBookKeeperClient(conf, statsLogger.scope(BookKeeperClientStats.CLIENT_SCOPE)); MetadataClientDriver metadataClientDriver = bkc.getMetadataClientDriver(); metadataClientDriver.setSessionStateListener(() -> { LOG.error("Client connection to the Metadata server has expired, so shutting down AutoRecoveryMain!"); // do not run "shutdown" in the main ZooKeeper client thread // as it performs some blocking operations CompletableFuture.runAsync(() -> { shutdown(ExitCode.ZK_EXPIRED); }); }); auditorElector = new AuditorElector( BookieImpl.getBookieId(conf).toString(), conf, bkc, statsLogger.scope(AUDITOR_SCOPE), false); replicationWorker = new ReplicationWorker( conf, bkc, false, statsLogger.scope(REPLICATION_WORKER_SCOPE)); deathWatcher = new AutoRecoveryDeathWatcher(this); } /* * Start daemons */ public void start() { auditorElector.start(); replicationWorker.start(); if (null != uncaughtExceptionHandler) { deathWatcher.setUncaughtExceptionHandler(uncaughtExceptionHandler); } deathWatcher.start(); running = true; } /* * Waits till all daemons joins */ public void join() throws InterruptedException { deathWatcher.join(); } /* * Shutdown all daemons gracefully */ public void shutdown() { shutdown(ExitCode.OK); } private void shutdown(int exitCode) { LOG.info("Shutting down auto recovery: {}", exitCode); if (shuttingDown) { return; } LOG.info("Shutting down AutoRecovery"); shuttingDown = true; running = false; this.exitCode = exitCode; try { auditorElector.shutdown(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.warn("Interrupted shutting down auditor elector", e); } replicationWorker.shutdown(); try { bkc.close(); } catch (BKException e) { LOG.warn("Failed to close bookkeeper client for auto recovery", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.warn("Interrupted closing bookkeeper client for auto recovery", e); } } private int getExitCode() { return exitCode; } /** * Currently the uncaught exception handler is used for DeathWatcher to notify * lifecycle management that a bookie is dead for some reasons. * * <p>in future, we can register this <tt>exceptionHandler</tt> to critical threads * so when those threads are dead, it will automatically trigger lifecycle management * to shutdown the process. */ public void setExceptionHandler(UncaughtExceptionHandler exceptionHandler) { this.uncaughtExceptionHandler = exceptionHandler; } @VisibleForTesting public Auditor getAuditor() { return auditorElector.getAuditor(); } @VisibleForTesting public ReplicationWorker getReplicationWorker() { return replicationWorker; } /** Is auto-recovery service running? */ public boolean isAutoRecoveryRunning() { return running; } /* * DeathWatcher for AutoRecovery daemons. */ private class AutoRecoveryDeathWatcher extends BookieCriticalThread { private int watchInterval; private AutoRecoveryMain autoRecoveryMain; public AutoRecoveryDeathWatcher(AutoRecoveryMain autoRecoveryMain) { super("AutoRecoveryDeathWatcher-" + autoRecoveryMain.conf.getBookiePort()); this.autoRecoveryMain = autoRecoveryMain; watchInterval = autoRecoveryMain.conf.getDeathWatchInterval(); // set a default uncaught exception handler to shutdown the AutoRecovery // when it notices the AutoRecovery is not running any more. setUncaughtExceptionHandler((thread, cause) -> { LOG.info("AutoRecoveryDeathWatcher exited loop due to uncaught exception from thread {}", thread.getName(), cause); shutdown(); }); } @Override public void run() { while (true) { try { Thread.sleep(watchInterval); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } // If any one service not running, then shutdown peer. if (!autoRecoveryMain.auditorElector.isRunning() || !autoRecoveryMain.replicationWorker.isRunning()) { LOG.info( "AutoRecoveryDeathWatcher noticed the AutoRecovery is not running any more," + "exiting the watch loop!"); /* * death watcher has noticed that AutoRecovery is not * running any more throw an exception to fail the death * watcher thread and it will trigger the uncaught exception * handler to handle this "AutoRecovery not running" * situation. */ throw new RuntimeException("AutoRecovery is not running any more"); } } } } private static final Options opts = new Options(); static { opts.addOption("c", "conf", true, "Bookie server configuration"); opts.addOption("h", "help", false, "Print help message"); } /* * Print usage */ private static void printUsage() { HelpFormatter hf = new HelpFormatter(); hf.printHelp("AutoRecoveryMain [options]\n", opts); } /* * load configurations from file. */ private static void loadConfFile(ServerConfiguration conf, String confFile) throws IllegalArgumentException { try { conf.loadConf(new File(confFile).toURI().toURL()); } catch (MalformedURLException e) { LOG.error("Could not open configuration file: " + confFile, e); throw new IllegalArgumentException(); } catch (ConfigurationException e) { LOG.error("Malformed configuration file: " + confFile, e); throw new IllegalArgumentException(); } LOG.info("Using configuration file " + confFile); } /* * Parse console args */ private static ServerConfiguration parseArgs(String[] args) throws IllegalArgumentException { try { BasicParser parser = new BasicParser(); CommandLine cmdLine = parser.parse(opts, args); if (cmdLine.hasOption('h')) { throw new IllegalArgumentException(); } ServerConfiguration conf = new ServerConfiguration(); String[] leftArgs = cmdLine.getArgs(); if (cmdLine.hasOption('c')) { if (null != leftArgs && leftArgs.length > 0) { throw new IllegalArgumentException("unexpected arguments [" + String.join(" ", leftArgs) + "]"); } String confFile = cmdLine.getOptionValue("c"); loadConfFile(conf, confFile); } if (null != leftArgs && leftArgs.length > 0) { throw new IllegalArgumentException("unexpected arguments [" + String.join(" ", leftArgs) + "]"); } return conf; } catch (ParseException e) { throw new IllegalArgumentException(e); } } public static void main(String[] args) { int retCode = doMain(args); Runtime.getRuntime().exit(retCode); } static int doMain(String[] args) { ServerConfiguration conf; // 0. parse command line try { conf = parseArgs(args); } catch (IllegalArgumentException iae) { LOG.error("Error parsing command line arguments : ", iae); if (iae.getMessage() != null) { System.err.println(iae.getMessage()); } printUsage(); return ExitCode.INVALID_CONF; } // 1. building the component stack: LifecycleComponent server; try { server = buildAutoRecoveryServer(new BookieConfiguration(conf)); } catch (Exception e) { LOG.error("Failed to build AutoRecovery Server", e); return ExitCode.SERVER_EXCEPTION; } // 2. start the server try { ComponentStarter.startComponent(server).get(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); // the server is interrupted LOG.info("AutoRecovery server is interrupted. Exiting ..."); } catch (ExecutionException ee) { LOG.error("Error in bookie shutdown", ee.getCause()); return ExitCode.SERVER_EXCEPTION; } return ExitCode.OK; } public static LifecycleComponentStack buildAutoRecoveryServer(BookieConfiguration conf) throws Exception { LifecycleComponentStack.Builder serverBuilder = LifecycleComponentStack.newBuilder() .withName("autorecovery-server"); // 1. build stats provider StatsProviderService statsProviderService = new StatsProviderService(conf); StatsLogger rootStatsLogger = statsProviderService.getStatsProvider().getStatsLogger(""); serverBuilder.addComponent(statsProviderService); LOG.info("Load lifecycle component : {}", StatsProviderService.class.getName()); // 2. build AutoRecovery server AutoRecoveryService autoRecoveryService = new AutoRecoveryService(conf, rootStatsLogger); serverBuilder.addComponent(autoRecoveryService); LOG.info("Load lifecycle component : {}", AutoRecoveryService.class.getName()); // 4. build http service if (conf.getServerConf().isHttpServerEnabled()) { BKHttpServiceProvider provider = new BKHttpServiceProvider.Builder() .setAutoRecovery(autoRecoveryService.getAutoRecoveryServer()) .setServerConfiguration(conf.getServerConf()) .setStatsProvider(statsProviderService.getStatsProvider()).build(); HttpService httpService = new HttpService(provider, conf, rootStatsLogger); serverBuilder.addComponent(httpService); LOG.info("Load lifecycle component : {}", HttpService.class.getName()); } return serverBuilder.build(); } }
285
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/AuditorCheckAllLedgersTask.java
/** * 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.bookkeeper.replication; import com.google.common.base.Stopwatch; import com.google.common.collect.Sets; import java.io.IOException; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import java.util.stream.Collectors; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.client.LedgerChecker; import org.apache.bookkeeper.client.LedgerFragment; import org.apache.bookkeeper.client.LedgerHandle; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks; import org.apache.bookkeeper.replication.ReplicationException.UnavailableException; import org.apache.zookeeper.AsyncCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AuditorCheckAllLedgersTask extends AuditorTask { private static final Logger LOG = LoggerFactory.getLogger(AuditorBookieCheckTask.class); private final Semaphore openLedgerNoRecoverySemaphore; private final int openLedgerNoRecoverySemaphoreWaitTimeoutMSec; private final ExecutorService ledgerCheckerExecutor; AuditorCheckAllLedgersTask(ServerConfiguration conf, AuditorStats auditorStats, BookKeeperAdmin admin, LedgerManager ledgerManager, LedgerUnderreplicationManager ledgerUnderreplicationManager, ShutdownTaskHandler shutdownTaskHandler, BiConsumer<AtomicBoolean, Throwable> hasAuditCheckTask) throws UnavailableException { super(conf, auditorStats, admin, ledgerManager, ledgerUnderreplicationManager, shutdownTaskHandler, hasAuditCheckTask); if (conf.getAuditorMaxNumberOfConcurrentOpenLedgerOperations() <= 0) { LOG.error("auditorMaxNumberOfConcurrentOpenLedgerOperations should be greater than 0"); throw new UnavailableException("auditorMaxNumberOfConcurrentOpenLedgerOperations should be greater than 0"); } this.openLedgerNoRecoverySemaphore = new Semaphore(conf.getAuditorMaxNumberOfConcurrentOpenLedgerOperations()); if (conf.getAuditorAcquireConcurrentOpenLedgerOperationsTimeoutMSec() < 0) { LOG.error("auditorAcquireConcurrentOpenLedgerOperationsTimeoutMSec should be greater than or equal to 0"); throw new UnavailableException("auditorAcquireConcurrentOpenLedgerOperationsTimeoutMSec " + "should be greater than or equal to 0"); } this.openLedgerNoRecoverySemaphoreWaitTimeoutMSec = conf.getAuditorAcquireConcurrentOpenLedgerOperationsTimeoutMSec(); this.ledgerCheckerExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "AuditorCheckAllLedgers-LedgerChecker"); t.setDaemon(true); return t; } }); } @Override protected void runTask() { if (hasBookieCheckTask()) { LOG.info("Audit bookie task already scheduled; skipping periodic all ledgers check task"); auditorStats.getNumSkippingCheckTaskTimes().inc(); return; } Stopwatch stopwatch = Stopwatch.createStarted(); boolean checkSuccess = false; try { if (!isLedgerReplicationEnabled()) { LOG.info("Ledger replication disabled, skipping checkAllLedgers"); checkSuccess = true; return; } LOG.info("Starting checkAllLedgers"); checkAllLedgers(); long checkAllLedgersDuration = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS); LOG.info("Completed checkAllLedgers in {} milliSeconds", checkAllLedgersDuration); auditorStats.getCheckAllLedgersTime() .registerSuccessfulEvent(checkAllLedgersDuration, TimeUnit.MILLISECONDS); checkSuccess = true; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.error("Interrupted while running periodic check", ie); } catch (BKException bke) { LOG.error("Exception running periodic check", bke); } catch (IOException ioe) { LOG.error("I/O exception running periodic check", ioe); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); } catch (ReplicationException.UnavailableException ue) { LOG.error("Underreplication manager unavailable running periodic check", ue); } finally { if (!checkSuccess) { long checkAllLedgersDuration = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS); auditorStats.getCheckAllLedgersTime() .registerFailedEvent(checkAllLedgersDuration, TimeUnit.MILLISECONDS); } } } @Override public void shutdown() { LOG.info("Shutting down AuditorCheckAllLedgersTask"); ledgerCheckerExecutor.shutdown(); try { while (!ledgerCheckerExecutor.awaitTermination(30, TimeUnit.SECONDS)) { LOG.warn("Executor for ledger checker not shutting down, interrupting"); ledgerCheckerExecutor.shutdownNow(); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.warn("Interrupted while shutting down AuditorCheckAllLedgersTask", ie); } } /** * List all the ledgers and check them individually. This should not * be run very often. */ void checkAllLedgers() throws BKException, IOException, InterruptedException { final BookKeeper localClient = getBookKeeper(conf); final BookKeeperAdmin localAdmin = getBookKeeperAdmin(localClient); try { final LedgerChecker checker = new LedgerChecker(localClient, conf.getInFlightReadEntryNumInLedgerChecker()); final CompletableFuture<Void> processFuture = new CompletableFuture<>(); BookkeeperInternalCallbacks.Processor<Long> checkLedgersProcessor = (ledgerId, callback) -> { try { if (!ledgerUnderreplicationManager.isLedgerReplicationEnabled()) { LOG.info("Ledger rereplication has been disabled, aborting periodic check"); FutureUtils.complete(processFuture, null); return; } } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); return; } catch (ReplicationException.UnavailableException ue) { LOG.error("Underreplication manager unavailable running periodic check", ue); FutureUtils.complete(processFuture, null); return; } try { if (!openLedgerNoRecoverySemaphore.tryAcquire(openLedgerNoRecoverySemaphoreWaitTimeoutMSec, TimeUnit.MILLISECONDS)) { LOG.warn("Failed to acquire semaphore for {} ms, ledgerId: {}", openLedgerNoRecoverySemaphoreWaitTimeoutMSec, ledgerId); FutureUtils.complete(processFuture, null); return; } } catch (InterruptedException e) { LOG.error("Unable to acquire open ledger operation semaphore ", e); Thread.currentThread().interrupt(); FutureUtils.complete(processFuture, null); return; } localAdmin.asyncOpenLedgerNoRecovery(ledgerId, (rc, lh, ctx) -> { openLedgerNoRecoverySemaphore.release(); if (BKException.Code.OK == rc) { // BookKeeperClientWorker-OrderedExecutor threads should not execute LedgerChecker#checkLedger // as this can lead to deadlocks ledgerCheckerExecutor.execute(() -> { checker.checkLedger(lh, // the ledger handle will be closed after checkLedger is done. new ProcessLostFragmentsCb(lh, callback), conf.getAuditorLedgerVerificationPercentage()); // we collect the following stats to get a measure of the // distribution of a single ledger within the bk cluster // the higher the number of fragments/bookies, the more distributed it is auditorStats.getNumFragmentsPerLedger().registerSuccessfulValue(lh.getNumFragments()); auditorStats.getNumBookiesPerLedger().registerSuccessfulValue(lh.getNumBookies()); auditorStats.getNumLedgersChecked().inc(); }); } else if (BKException.Code.NoSuchLedgerExistsOnMetadataServerException == rc) { if (LOG.isDebugEnabled()) { LOG.debug("Ledger {} was deleted before we could check it", ledgerId); } callback.processResult(BKException.Code.OK, null, null); } else { LOG.error("Couldn't open ledger {} to check : {}", ledgerId, BKException.getMessage(rc)); callback.processResult(rc, null, null); } }, null); }; ledgerManager.asyncProcessLedgers(checkLedgersProcessor, (rc, path, ctx) -> { if (BKException.Code.OK == rc) { FutureUtils.complete(processFuture, null); } else { FutureUtils.completeExceptionally(processFuture, BKException.create(rc)); } }, null, BKException.Code.OK, BKException.Code.ReadException); FutureUtils.result(processFuture, BKException.HANDLER); try { ledgerUnderreplicationManager.setCheckAllLedgersCTime(System.currentTimeMillis()); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); } catch (ReplicationException.UnavailableException ue) { LOG.error("Got exception while trying to set checkAllLedgersCTime", ue); } } finally { localAdmin.close(); localClient.close(); } } /** * Process the result returned from checking a ledger. */ private class ProcessLostFragmentsCb implements BookkeeperInternalCallbacks.GenericCallback<Set<LedgerFragment>> { final LedgerHandle lh; final AsyncCallback.VoidCallback callback; ProcessLostFragmentsCb(LedgerHandle lh, AsyncCallback.VoidCallback callback) { this.lh = lh; this.callback = callback; } @Override public void operationComplete(int rc, Set<LedgerFragment> fragments) { if (rc == BKException.Code.OK) { Set<BookieId> bookies = Sets.newHashSet(); for (LedgerFragment f : fragments) { bookies.addAll(f.getAddresses()); } if (bookies.isEmpty()) { // no missing fragments callback.processResult(BKException.Code.OK, null, null); } else { publishSuspectedLedgersAsync(bookies.stream().map(BookieId::toString).collect(Collectors.toList()), Sets.newHashSet(lh.getId()) ).whenComplete((result, cause) -> { if (null != cause) { LOG.error("Auditor exception publishing suspected ledger {} with lost bookies {}", lh.getId(), bookies, cause); callback.processResult(BKException.Code.ReplicationException, null, null); } else { callback.processResult(BKException.Code.OK, null, null); } }); } } else { callback.processResult(rc, null, null); } lh.closeAsync().whenComplete((result, cause) -> { if (null != cause) { LOG.warn("Error closing ledger {} : {}", lh.getId(), cause.getMessage()); } }); } } }
286
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/AuditorStats.java
/** * 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.bookkeeper.replication; import static org.apache.bookkeeper.replication.ReplicationStats.AUDITOR_SCOPE; import static org.apache.bookkeeper.replication.ReplicationStats.AUDIT_BOOKIES_TIME; import static org.apache.bookkeeper.replication.ReplicationStats.BOOKIE_TO_LEDGERS_MAP_CREATION_TIME; import static org.apache.bookkeeper.replication.ReplicationStats.CHECK_ALL_LEDGERS_TIME; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_BOOKIES_PER_LEDGER; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_BOOKIE_AUDITS_DELAYED; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_DELAYED_BOOKIE_AUDITS_DELAYES_CANCELLED; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_FRAGMENTS_PER_LEDGER; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_LEDGERS_CHECKED; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_LEDGERS_HAVING_LESS_THAN_AQ_REPLICAS_OF_AN_ENTRY; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_LEDGERS_HAVING_LESS_THAN_WQ_REPLICAS_OF_AN_ENTRY; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_LEDGERS_HAVING_NO_REPLICA_OF_AN_ENTRY; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_LEDGERS_NOT_ADHERING_TO_PLACEMENT_POLICY; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_LEDGERS_SOFTLY_ADHERING_TO_PLACEMENT_POLICY; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_SKIPPING_CHECK_TASK_TIMES; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_UNDERREPLICATED_LEDGERS_ELAPSED_RECOVERY_GRACE_PERIOD; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_UNDER_REPLICATED_LEDGERS; import static org.apache.bookkeeper.replication.ReplicationStats.PLACEMENT_POLICY_CHECK_TIME; import static org.apache.bookkeeper.replication.ReplicationStats.REPLICAS_CHECK_TIME; import static org.apache.bookkeeper.replication.ReplicationStats.UNDER_REPLICATED_LEDGERS_TOTAL_SIZE; import static org.apache.bookkeeper.replication.ReplicationStats.URL_PUBLISH_TIME_FOR_LOST_BOOKIE; import java.util.concurrent.atomic.AtomicInteger; import lombok.Getter; import org.apache.bookkeeper.stats.Counter; import org.apache.bookkeeper.stats.Gauge; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.stats.annotations.StatsDoc; @StatsDoc( name = AUDITOR_SCOPE, help = "Auditor related stats" ) @Getter public class AuditorStats { private final AtomicInteger ledgersNotAdheringToPlacementPolicyGuageValue; private final AtomicInteger ledgersSoftlyAdheringToPlacementPolicyGuageValue; private final AtomicInteger numOfURLedgersElapsedRecoveryGracePeriodGuageValue; private final AtomicInteger numLedgersHavingNoReplicaOfAnEntryGuageValue; private final AtomicInteger numLedgersHavingLessThanAQReplicasOfAnEntryGuageValue; private final AtomicInteger numLedgersHavingLessThanWQReplicasOfAnEntryGuageValue; private final AtomicInteger underReplicatedLedgersGuageValue; private final StatsLogger statsLogger; @StatsDoc( name = NUM_UNDER_REPLICATED_LEDGERS, help = "the distribution of num under_replicated ledgers on each auditor run" ) private final OpStatsLogger numUnderReplicatedLedger; @StatsDoc( name = UNDER_REPLICATED_LEDGERS_TOTAL_SIZE, help = "the distribution of under_replicated ledgers total size on each auditor run" ) private final OpStatsLogger underReplicatedLedgerTotalSize; @StatsDoc( name = URL_PUBLISH_TIME_FOR_LOST_BOOKIE, help = "the latency distribution of publishing under replicated ledgers for lost bookies" ) private final OpStatsLogger uRLPublishTimeForLostBookies; @StatsDoc( name = BOOKIE_TO_LEDGERS_MAP_CREATION_TIME, help = "the latency distribution of creating bookies-to-ledgers map" ) private final OpStatsLogger bookieToLedgersMapCreationTime; @StatsDoc( name = CHECK_ALL_LEDGERS_TIME, help = "the latency distribution of checking all ledgers" ) private final OpStatsLogger checkAllLedgersTime; @StatsDoc( name = PLACEMENT_POLICY_CHECK_TIME, help = "the latency distribution of placementPolicy check" ) private final OpStatsLogger placementPolicyCheckTime; @StatsDoc( name = REPLICAS_CHECK_TIME, help = "the latency distribution of replicas check" ) private final OpStatsLogger replicasCheckTime; @StatsDoc( name = AUDIT_BOOKIES_TIME, help = "the latency distribution of auditing all the bookies" ) private final OpStatsLogger auditBookiesTime; @StatsDoc( name = NUM_LEDGERS_CHECKED, help = "the number of ledgers checked by the auditor" ) private final Counter numLedgersChecked; @StatsDoc( name = NUM_FRAGMENTS_PER_LEDGER, help = "the distribution of number of fragments per ledger" ) private final OpStatsLogger numFragmentsPerLedger; @StatsDoc( name = NUM_BOOKIES_PER_LEDGER, help = "the distribution of number of bookies per ledger" ) private final OpStatsLogger numBookiesPerLedger; @StatsDoc( name = NUM_BOOKIE_AUDITS_DELAYED, help = "the number of bookie-audits delayed" ) private final Counter numBookieAuditsDelayed; @StatsDoc( name = NUM_DELAYED_BOOKIE_AUDITS_DELAYES_CANCELLED, help = "the number of delayed-bookie-audits cancelled" ) private final Counter numDelayedBookieAuditsCancelled; @StatsDoc( name = NUM_LEDGERS_NOT_ADHERING_TO_PLACEMENT_POLICY, help = "Gauge for number of ledgers not adhering to placement policy found in placement policy check" ) private final Gauge<Integer> numLedgersNotAdheringToPlacementPolicy; @StatsDoc( name = NUM_LEDGERS_SOFTLY_ADHERING_TO_PLACEMENT_POLICY, help = "Gauge for number of ledgers softly adhering to placement policy found in placement policy check" ) private final Gauge<Integer> numLedgersSoftlyAdheringToPlacementPolicy; @StatsDoc( name = NUM_UNDERREPLICATED_LEDGERS_ELAPSED_RECOVERY_GRACE_PERIOD, help = "Gauge for number of underreplicated ledgers elapsed recovery grace period" ) private final Gauge<Integer> numUnderreplicatedLedgersElapsedRecoveryGracePeriod; @StatsDoc( name = NUM_LEDGERS_HAVING_NO_REPLICA_OF_AN_ENTRY, help = "Gauge for number of ledgers having an entry with all the replicas missing" ) private final Gauge<Integer> numLedgersHavingNoReplicaOfAnEntry; @StatsDoc( name = NUM_LEDGERS_HAVING_LESS_THAN_AQ_REPLICAS_OF_AN_ENTRY, help = "Gauge for number of ledgers having an entry with less than AQ number of replicas" + ", this doesn't include ledgers counted towards numLedgersHavingNoReplicaOfAnEntry" ) private final Gauge<Integer> numLedgersHavingLessThanAQReplicasOfAnEntry; @StatsDoc( name = NUM_LEDGERS_HAVING_LESS_THAN_WQ_REPLICAS_OF_AN_ENTRY, help = "Gauge for number of ledgers having an entry with less than WQ number of replicas" + ", this doesn't include ledgers counted towards numLedgersHavingLessThanAQReplicasOfAnEntry" ) private final Gauge<Integer> numLedgersHavingLessThanWQReplicasOfAnEntry; @StatsDoc( name = NUM_SKIPPING_CHECK_TASK_TIMES, help = "the times of auditor check task skipped" ) private final Counter numSkippingCheckTaskTimes; public AuditorStats(StatsLogger statsLogger) { this.statsLogger = statsLogger; this.ledgersNotAdheringToPlacementPolicyGuageValue = new AtomicInteger(0); this.ledgersSoftlyAdheringToPlacementPolicyGuageValue = new AtomicInteger(0); this.numOfURLedgersElapsedRecoveryGracePeriodGuageValue = new AtomicInteger(0); this.numLedgersHavingNoReplicaOfAnEntryGuageValue = new AtomicInteger(0); this.numLedgersHavingLessThanAQReplicasOfAnEntryGuageValue = new AtomicInteger(0); this.numLedgersHavingLessThanWQReplicasOfAnEntryGuageValue = new AtomicInteger(0); this.underReplicatedLedgersGuageValue = new AtomicInteger(0); numUnderReplicatedLedger = this.statsLogger.getOpStatsLogger(ReplicationStats.NUM_UNDER_REPLICATED_LEDGERS); underReplicatedLedgerTotalSize = this.statsLogger.getOpStatsLogger(UNDER_REPLICATED_LEDGERS_TOTAL_SIZE); uRLPublishTimeForLostBookies = this.statsLogger .getOpStatsLogger(ReplicationStats.URL_PUBLISH_TIME_FOR_LOST_BOOKIE); bookieToLedgersMapCreationTime = this.statsLogger .getOpStatsLogger(ReplicationStats.BOOKIE_TO_LEDGERS_MAP_CREATION_TIME); checkAllLedgersTime = this.statsLogger.getOpStatsLogger(ReplicationStats.CHECK_ALL_LEDGERS_TIME); placementPolicyCheckTime = this.statsLogger.getOpStatsLogger(ReplicationStats.PLACEMENT_POLICY_CHECK_TIME); replicasCheckTime = this.statsLogger.getOpStatsLogger(ReplicationStats.REPLICAS_CHECK_TIME); auditBookiesTime = this.statsLogger.getOpStatsLogger(ReplicationStats.AUDIT_BOOKIES_TIME); numLedgersChecked = this.statsLogger.getCounter(ReplicationStats.NUM_LEDGERS_CHECKED); numFragmentsPerLedger = this.statsLogger.getOpStatsLogger(ReplicationStats.NUM_FRAGMENTS_PER_LEDGER); numBookiesPerLedger = this.statsLogger.getOpStatsLogger(ReplicationStats.NUM_BOOKIES_PER_LEDGER); numBookieAuditsDelayed = this.statsLogger.getCounter(ReplicationStats.NUM_BOOKIE_AUDITS_DELAYED); numDelayedBookieAuditsCancelled = this.statsLogger .getCounter(ReplicationStats.NUM_DELAYED_BOOKIE_AUDITS_DELAYES_CANCELLED); numSkippingCheckTaskTimes = this.statsLogger.getCounter(NUM_SKIPPING_CHECK_TASK_TIMES); numLedgersNotAdheringToPlacementPolicy = new Gauge<Integer>() { @Override public Integer getDefaultValue() { return 0; } @Override public Integer getSample() { return ledgersNotAdheringToPlacementPolicyGuageValue.get(); } }; this.statsLogger.registerGauge(ReplicationStats.NUM_LEDGERS_NOT_ADHERING_TO_PLACEMENT_POLICY, numLedgersNotAdheringToPlacementPolicy); numLedgersSoftlyAdheringToPlacementPolicy = new Gauge<Integer>() { @Override public Integer getDefaultValue() { return 0; } @Override public Integer getSample() { return ledgersSoftlyAdheringToPlacementPolicyGuageValue.get(); } }; this.statsLogger.registerGauge(ReplicationStats.NUM_LEDGERS_SOFTLY_ADHERING_TO_PLACEMENT_POLICY, numLedgersSoftlyAdheringToPlacementPolicy); numUnderreplicatedLedgersElapsedRecoveryGracePeriod = new Gauge<Integer>() { @Override public Integer getDefaultValue() { return 0; } @Override public Integer getSample() { return numOfURLedgersElapsedRecoveryGracePeriodGuageValue.get(); } }; this.statsLogger.registerGauge(ReplicationStats.NUM_UNDERREPLICATED_LEDGERS_ELAPSED_RECOVERY_GRACE_PERIOD, numUnderreplicatedLedgersElapsedRecoveryGracePeriod); numLedgersHavingNoReplicaOfAnEntry = new Gauge<Integer>() { @Override public Integer getDefaultValue() { return 0; } @Override public Integer getSample() { return numLedgersHavingNoReplicaOfAnEntryGuageValue.get(); } }; this.statsLogger.registerGauge(ReplicationStats.NUM_LEDGERS_HAVING_NO_REPLICA_OF_AN_ENTRY, numLedgersHavingNoReplicaOfAnEntry); numLedgersHavingLessThanAQReplicasOfAnEntry = new Gauge<Integer>() { @Override public Integer getDefaultValue() { return 0; } @Override public Integer getSample() { return numLedgersHavingLessThanAQReplicasOfAnEntryGuageValue.get(); } }; this.statsLogger.registerGauge(ReplicationStats.NUM_LEDGERS_HAVING_LESS_THAN_AQ_REPLICAS_OF_AN_ENTRY, numLedgersHavingLessThanAQReplicasOfAnEntry); numLedgersHavingLessThanWQReplicasOfAnEntry = new Gauge<Integer>() { @Override public Integer getDefaultValue() { return 0; } @Override public Integer getSample() { return numLedgersHavingLessThanWQReplicasOfAnEntryGuageValue.get(); } }; this.statsLogger.registerGauge(ReplicationStats.NUM_LEDGERS_HAVING_LESS_THAN_WQ_REPLICAS_OF_AN_ENTRY, numLedgersHavingLessThanWQReplicasOfAnEntry); } }
287
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/AuditorReplicasCheckTask.java
/** * 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.bookkeeper.replication; import com.google.common.base.Stopwatch; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import java.io.IOException; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.client.RoundRobinDistributionSchedule; import org.apache.bookkeeper.client.api.LedgerMetadata; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.MultiCallback; import org.apache.bookkeeper.util.AvailabilityOfEntriesOfLedger; import org.apache.bookkeeper.versioning.Versioned; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.AsyncCallback.VoidCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AuditorReplicasCheckTask extends AuditorTask { private static final Logger LOG = LoggerFactory.getLogger(AuditorReplicasCheckTask.class); private static final int MAX_CONCURRENT_REPLICAS_CHECK_LEDGER_REQUESTS = 100; private static final int REPLICAS_CHECK_TIMEOUT_IN_SECS = 120; private static final BitSet EMPTY_BITSET = new BitSet(); private final int zkOpTimeoutMs; private final AtomicInteger numLedgersFoundHavingNoReplicaOfAnEntry; private final AtomicInteger numLedgersFoundHavingLessThanAQReplicasOfAnEntry; private final AtomicInteger numLedgersFoundHavingLessThanWQReplicasOfAnEntry; AuditorReplicasCheckTask(ServerConfiguration conf, AuditorStats auditorStats, BookKeeperAdmin admin, LedgerManager ledgerManager, LedgerUnderreplicationManager ledgerUnderreplicationManager, ShutdownTaskHandler shutdownTaskHandler, BiConsumer<AtomicBoolean, Throwable> hasAuditCheckTask) { super(conf, auditorStats, admin, ledgerManager, ledgerUnderreplicationManager, shutdownTaskHandler, hasAuditCheckTask); this.zkOpTimeoutMs = conf.getZkTimeout() * 2; this.numLedgersFoundHavingNoReplicaOfAnEntry = new AtomicInteger(0); this.numLedgersFoundHavingLessThanAQReplicasOfAnEntry = new AtomicInteger(0); this.numLedgersFoundHavingLessThanWQReplicasOfAnEntry = new AtomicInteger(0); } @Override protected void runTask() { if (hasBookieCheckTask()) { LOG.info("Audit bookie task already scheduled; skipping periodic replicas check task"); auditorStats.getNumSkippingCheckTaskTimes().inc(); return; } try { if (!ledgerUnderreplicationManager.isLedgerReplicationEnabled()) { LOG.info("Ledger replication disabled, skipping replicasCheck task."); return; } Stopwatch stopwatch = Stopwatch.createStarted(); LOG.info("Starting ReplicasCheck"); replicasCheck(); long replicasCheckDuration = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS); int numLedgersFoundHavingNoReplicaOfAnEntryValue = numLedgersFoundHavingNoReplicaOfAnEntry.get(); int numLedgersFoundHavingLessThanAQReplicasOfAnEntryValue = numLedgersFoundHavingLessThanAQReplicasOfAnEntry.get(); int numLedgersFoundHavingLessThanWQReplicasOfAnEntryValue = numLedgersFoundHavingLessThanWQReplicasOfAnEntry.get(); LOG.info( "Completed ReplicasCheck in {} milliSeconds numLedgersFoundHavingNoReplicaOfAnEntry {}" + " numLedgersFoundHavingLessThanAQReplicasOfAnEntry {}" + " numLedgersFoundHavingLessThanWQReplicasOfAnEntry {}.", replicasCheckDuration, numLedgersFoundHavingNoReplicaOfAnEntryValue, numLedgersFoundHavingLessThanAQReplicasOfAnEntryValue, numLedgersFoundHavingLessThanWQReplicasOfAnEntryValue); auditorStats.getNumLedgersHavingNoReplicaOfAnEntryGuageValue() .set(numLedgersFoundHavingNoReplicaOfAnEntryValue); auditorStats.getNumLedgersHavingLessThanAQReplicasOfAnEntryGuageValue() .set(numLedgersFoundHavingLessThanAQReplicasOfAnEntryValue); auditorStats.getNumLedgersHavingLessThanWQReplicasOfAnEntryGuageValue() .set(numLedgersFoundHavingLessThanWQReplicasOfAnEntryValue); auditorStats.getReplicasCheckTime().registerSuccessfulEvent( replicasCheckDuration, TimeUnit.MILLISECONDS); } catch (ReplicationException.BKAuditException e) { LOG.error("BKAuditException running periodic replicas check.", e); int numLedgersFoundHavingNoReplicaOfAnEntryValue = numLedgersFoundHavingNoReplicaOfAnEntry.get(); if (numLedgersFoundHavingNoReplicaOfAnEntryValue > 0) { /* * Though there is BKAuditException while doing * replicasCheck, it found few ledgers having no replica * of an entry. So reporting it. */ auditorStats.getNumLedgersHavingNoReplicaOfAnEntryGuageValue() .set(numLedgersFoundHavingNoReplicaOfAnEntryValue); } int numLedgersFoundHavingLessThanAQReplicasOfAnEntryValue = numLedgersFoundHavingLessThanAQReplicasOfAnEntry.get(); if (numLedgersFoundHavingLessThanAQReplicasOfAnEntryValue > 0) { /* * Though there is BKAuditException while doing * replicasCheck, it found few ledgers having an entry * less than AQ num of Replicas. So reporting it. */ auditorStats.getNumLedgersHavingLessThanAQReplicasOfAnEntryGuageValue() .set(numLedgersFoundHavingLessThanAQReplicasOfAnEntryValue); } int numLedgersFoundHavingLessThanWQReplicasOfAnEntryValue = numLedgersFoundHavingLessThanWQReplicasOfAnEntry.get(); if (numLedgersFoundHavingLessThanWQReplicasOfAnEntryValue > 0) { /* * Though there is BKAuditException while doing * replicasCheck, it found few ledgers having an entry * less than WQ num of Replicas. So reporting it. */ auditorStats.getNumLedgersHavingLessThanWQReplicasOfAnEntryGuageValue() .set(numLedgersFoundHavingLessThanWQReplicasOfAnEntryValue); } } catch (ReplicationException.UnavailableException ue) { LOG.error("Underreplication manager unavailable running periodic check", ue); } } @Override public void shutdown() { } void replicasCheck() throws ReplicationException.BKAuditException { ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithMissingEntries = new ConcurrentHashMap<Long, MissingEntriesInfoOfLedger>(); ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithUnavailableBookies = new ConcurrentHashMap<Long, MissingEntriesInfoOfLedger>(); LedgerManager.LedgerRangeIterator ledgerRangeIterator = ledgerManager.getLedgerRanges(zkOpTimeoutMs); final Semaphore maxConcurrentSemaphore = new Semaphore(MAX_CONCURRENT_REPLICAS_CHECK_LEDGER_REQUESTS); while (true) { LedgerManager.LedgerRange ledgerRange = null; try { if (ledgerRangeIterator.hasNext()) { ledgerRange = ledgerRangeIterator.next(); } else { break; } } catch (IOException ioe) { LOG.error("Got IOException while iterating LedgerRangeIterator", ioe); throw new ReplicationException.BKAuditException( "Got IOException while iterating LedgerRangeIterator", ioe); } ledgersWithMissingEntries.clear(); ledgersWithUnavailableBookies.clear(); numLedgersFoundHavingNoReplicaOfAnEntry.set(0); numLedgersFoundHavingLessThanAQReplicasOfAnEntry.set(0); numLedgersFoundHavingLessThanWQReplicasOfAnEntry.set(0); Set<Long> ledgersInRange = ledgerRange.getLedgers(); int numOfLedgersInRange = ledgersInRange.size(); // Final result after processing all the ledgers final AtomicInteger resultCode = new AtomicInteger(); final CountDownLatch replicasCheckLatch = new CountDownLatch(1); ReplicasCheckFinalCallback finalCB = new ReplicasCheckFinalCallback(resultCode, replicasCheckLatch); MultiCallback mcbForThisLedgerRange = new MultiCallback(numOfLedgersInRange, finalCB, null, BKException.Code.OK, BKException.Code.ReadException) { @Override public void processResult(int rc, String path, Object ctx) { try { super.processResult(rc, path, ctx); } finally { maxConcurrentSemaphore.release(); } } }; if (LOG.isDebugEnabled()) { LOG.debug("Number of ledgers in the current LedgerRange : {}", numOfLedgersInRange); } for (Long ledgerInRange : ledgersInRange) { try { if (!maxConcurrentSemaphore.tryAcquire(REPLICAS_CHECK_TIMEOUT_IN_SECS, TimeUnit.SECONDS)) { LOG.error("Timedout ({} secs) while waiting for acquiring semaphore", REPLICAS_CHECK_TIMEOUT_IN_SECS); throw new ReplicationException.BKAuditException( "Timedout while waiting for acquiring semaphore"); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.error("Got InterruptedException while acquiring semaphore for replicascheck", ie); throw new ReplicationException.BKAuditException( "Got InterruptedException while acquiring semaphore for replicascheck", ie); } if (checkUnderReplicationForReplicasCheck(ledgerInRange, mcbForThisLedgerRange)) { /* * if ledger is marked underreplicated, then ignore this * ledger for replicascheck. */ continue; } ledgerManager.readLedgerMetadata(ledgerInRange) .whenComplete(new ReadLedgerMetadataCallbackForReplicasCheck(ledgerInRange, mcbForThisLedgerRange, ledgersWithMissingEntries, ledgersWithUnavailableBookies)); } try { /* * if mcbForThisLedgerRange is not calledback within * REPLICAS_CHECK_TIMEOUT_IN_SECS secs then better give up * doing replicascheck, since there could be an issue and * blocking the single threaded auditor executor thread is not * expected. */ if (!replicasCheckLatch.await(REPLICAS_CHECK_TIMEOUT_IN_SECS, TimeUnit.SECONDS)) { LOG.error( "For LedgerRange with num of ledgers : {} it didn't complete replicascheck" + " in {} secs, so giving up", numOfLedgersInRange, REPLICAS_CHECK_TIMEOUT_IN_SECS); throw new ReplicationException.BKAuditException( "Got InterruptedException while doing replicascheck"); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.error("Got InterruptedException while doing replicascheck", ie); throw new ReplicationException.BKAuditException( "Got InterruptedException while doing replicascheck", ie); } reportLedgersWithMissingEntries(ledgersWithMissingEntries); reportLedgersWithUnavailableBookies(ledgersWithUnavailableBookies); int resultCodeIntValue = resultCode.get(); if (resultCodeIntValue != BKException.Code.OK) { throw new ReplicationException.BKAuditException("Exception while doing replicas check", BKException.create(resultCodeIntValue)); } } try { ledgerUnderreplicationManager.setReplicasCheckCTime(System.currentTimeMillis()); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); } catch (ReplicationException.UnavailableException ue) { LOG.error("Got exception while trying to set ReplicasCheckCTime", ue); } } private static class MissingEntriesInfo { // ledger id of missing entries private final long ledgerId; /* * segment details, like start entryid of the segment and ensemble List. */ private final Entry<Long, ? extends List<BookieId>> segmentEnsemble; // bookie missing these entries private final BookieId bookieMissingEntries; /* * entries of this segment which are supposed to contain in this bookie * but missing in this bookie. */ private final List<Long> unavailableEntriesList; private MissingEntriesInfo(long ledgerId, Entry<Long, ? extends List<BookieId>> segmentEnsemble, BookieId bookieMissingEntries, List<Long> unavailableEntriesList) { this.ledgerId = ledgerId; this.segmentEnsemble = segmentEnsemble; this.bookieMissingEntries = bookieMissingEntries; this.unavailableEntriesList = unavailableEntriesList; } private long getLedgerId() { return ledgerId; } private Entry<Long, ? extends List<BookieId>> getSegmentEnsemble() { return segmentEnsemble; } private BookieId getBookieMissingEntries() { return bookieMissingEntries; } private List<Long> getUnavailableEntriesList() { return unavailableEntriesList; } } private static class MissingEntriesInfoOfLedger { private final long ledgerId; private final int ensembleSize; private final int writeQuorumSize; private final int ackQuorumSize; private final List<MissingEntriesInfo> missingEntriesInfoList; private MissingEntriesInfoOfLedger(long ledgerId, int ensembleSize, int writeQuorumSize, int ackQuorumSize, List<MissingEntriesInfo> missingEntriesInfoList) { this.ledgerId = ledgerId; this.ensembleSize = ensembleSize; this.writeQuorumSize = writeQuorumSize; this.ackQuorumSize = ackQuorumSize; this.missingEntriesInfoList = missingEntriesInfoList; } private long getLedgerId() { return ledgerId; } private int getEnsembleSize() { return ensembleSize; } private int getWriteQuorumSize() { return writeQuorumSize; } private int getAckQuorumSize() { return ackQuorumSize; } private List<MissingEntriesInfo> getMissingEntriesInfoList() { return missingEntriesInfoList; } } private class ReadLedgerMetadataCallbackForReplicasCheck implements BiConsumer<Versioned<LedgerMetadata>, Throwable> { private final long ledgerInRange; private final MultiCallback mcbForThisLedgerRange; private final ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithMissingEntries; private final ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithUnavailableBookies; ReadLedgerMetadataCallbackForReplicasCheck( long ledgerInRange, MultiCallback mcbForThisLedgerRange, ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithMissingEntries, ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithUnavailableBookies) { this.ledgerInRange = ledgerInRange; this.mcbForThisLedgerRange = mcbForThisLedgerRange; this.ledgersWithMissingEntries = ledgersWithMissingEntries; this.ledgersWithUnavailableBookies = ledgersWithUnavailableBookies; } @Override public void accept(Versioned<LedgerMetadata> metadataVer, Throwable exception) { if (exception != null) { if (BKException .getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsOnMetadataServerException) { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring replicas check of already deleted ledger {}", ledgerInRange); } mcbForThisLedgerRange.processResult(BKException.Code.OK, null, null); return; } else { LOG.warn("Unable to read the ledger: {} information", ledgerInRange, exception); mcbForThisLedgerRange.processResult(BKException.getExceptionCode(exception), null, null); return; } } LedgerMetadata metadata = metadataVer.getValue(); if (!metadata.isClosed()) { if (LOG.isDebugEnabled()) { LOG.debug("Ledger: {} is not yet closed, " + "so skipping the replicas check analysis for now", ledgerInRange); } mcbForThisLedgerRange.processResult(BKException.Code.OK, null, null); return; } final long lastEntryId = metadata.getLastEntryId(); if (lastEntryId == -1) { if (LOG.isDebugEnabled()) { LOG.debug("Ledger: {} is closed but it doesn't has any entries, " + "so skipping the replicas check", ledgerInRange); } mcbForThisLedgerRange.processResult(BKException.Code.OK, null, null); return; } int writeQuorumSize = metadata.getWriteQuorumSize(); int ackQuorumSize = metadata.getAckQuorumSize(); int ensembleSize = metadata.getEnsembleSize(); RoundRobinDistributionSchedule distributionSchedule = new RoundRobinDistributionSchedule(writeQuorumSize, ackQuorumSize, ensembleSize); List<Entry<Long, ? extends List<BookieId>>> segments = new LinkedList<>( metadata.getAllEnsembles().entrySet()); /* * since there are multiple segments, MultiCallback should be * created for (ensembleSize * segments.size()) calls. */ MultiCallback mcbForThisLedger = new MultiCallback(ensembleSize * segments.size(), mcbForThisLedgerRange, null, BKException.Code.OK, BKException.Code.ReadException); HashMap<BookieId, List<BookieExpectedToContainSegmentInfo>> bookiesSegmentInfoMap = new HashMap<BookieId, List<BookieExpectedToContainSegmentInfo>>(); for (int segmentNum = 0; segmentNum < segments.size(); segmentNum++) { final Entry<Long, ? extends List<BookieId>> segmentEnsemble = segments.get(segmentNum); final List<BookieId> ensembleOfSegment = segmentEnsemble.getValue(); final long startEntryIdOfSegment = segmentEnsemble.getKey(); final boolean lastSegment = (segmentNum == (segments.size() - 1)); final long lastEntryIdOfSegment = lastSegment ? lastEntryId : segments.get(segmentNum + 1).getKey() - 1; /* * Segment can be empty. If last segment is empty, then * startEntryIdOfSegment of it will be greater than lastEntryId * of the ledger. If the segment in middle is empty, then its * startEntry will be same as startEntry of the following * segment. */ final boolean emptySegment = lastSegment ? (startEntryIdOfSegment > lastEntryId) : (startEntryIdOfSegment == segments.get(segmentNum + 1).getKey()); for (int bookieIndex = 0; bookieIndex < ensembleOfSegment.size(); bookieIndex++) { final BookieId bookieInEnsemble = ensembleOfSegment.get(bookieIndex); final BitSet entriesStripedToThisBookie = emptySegment ? EMPTY_BITSET : distributionSchedule.getEntriesStripedToTheBookie(bookieIndex, startEntryIdOfSegment, lastEntryIdOfSegment); if (entriesStripedToThisBookie.cardinality() == 0) { /* * if no entry is expected to contain in this bookie, * then there is no point in making * getListOfEntriesOfLedger call for this bookie. So * instead callback with success result. */ if (LOG.isDebugEnabled()) { LOG.debug( "For ledger: {}, in Segment: {}, no entry is expected to contain in" + " this bookie: {}. So skipping getListOfEntriesOfLedger call", ledgerInRange, segmentEnsemble, bookieInEnsemble); } mcbForThisLedger.processResult(BKException.Code.OK, null, null); continue; } List<BookieExpectedToContainSegmentInfo> bookieSegmentInfoList = bookiesSegmentInfoMap .get(bookieInEnsemble); if (bookieSegmentInfoList == null) { bookieSegmentInfoList = new ArrayList<BookieExpectedToContainSegmentInfo>(); bookiesSegmentInfoMap.put(bookieInEnsemble, bookieSegmentInfoList); } bookieSegmentInfoList.add(new BookieExpectedToContainSegmentInfo(startEntryIdOfSegment, lastEntryIdOfSegment, segmentEnsemble, entriesStripedToThisBookie)); } } for (Entry<BookieId, List<BookieExpectedToContainSegmentInfo>> bookiesSegmentInfoTuple : bookiesSegmentInfoMap.entrySet()) { final BookieId bookieInEnsemble = bookiesSegmentInfoTuple.getKey(); final List<BookieExpectedToContainSegmentInfo> bookieSegmentInfoList = bookiesSegmentInfoTuple .getValue(); admin.asyncGetListOfEntriesOfLedger(bookieInEnsemble, ledgerInRange) .whenComplete(new GetListOfEntriesOfLedgerCallbackForReplicasCheck(ledgerInRange, ensembleSize, writeQuorumSize, ackQuorumSize, bookieInEnsemble, bookieSegmentInfoList, ledgersWithMissingEntries, ledgersWithUnavailableBookies, mcbForThisLedger)); } } } private static class BookieExpectedToContainSegmentInfo { private final long startEntryIdOfSegment; private final long lastEntryIdOfSegment; private final Entry<Long, ? extends List<BookieId>> segmentEnsemble; private final BitSet entriesOfSegmentStripedToThisBookie; private BookieExpectedToContainSegmentInfo(long startEntryIdOfSegment, long lastEntryIdOfSegment, Entry<Long, ? extends List<BookieId>> segmentEnsemble, BitSet entriesOfSegmentStripedToThisBookie) { this.startEntryIdOfSegment = startEntryIdOfSegment; this.lastEntryIdOfSegment = lastEntryIdOfSegment; this.segmentEnsemble = segmentEnsemble; this.entriesOfSegmentStripedToThisBookie = entriesOfSegmentStripedToThisBookie; } public long getStartEntryIdOfSegment() { return startEntryIdOfSegment; } public long getLastEntryIdOfSegment() { return lastEntryIdOfSegment; } public Entry<Long, ? extends List<BookieId>> getSegmentEnsemble() { return segmentEnsemble; } public BitSet getEntriesOfSegmentStripedToThisBookie() { return entriesOfSegmentStripedToThisBookie; } } private static class GetListOfEntriesOfLedgerCallbackForReplicasCheck implements BiConsumer<AvailabilityOfEntriesOfLedger, Throwable> { private final long ledgerInRange; private final int ensembleSize; private final int writeQuorumSize; private final int ackQuorumSize; private final BookieId bookieInEnsemble; private final List<BookieExpectedToContainSegmentInfo> bookieExpectedToContainSegmentInfoList; private final ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithMissingEntries; private final ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithUnavailableBookies; private final MultiCallback mcbForThisLedger; private GetListOfEntriesOfLedgerCallbackForReplicasCheck( long ledgerInRange, int ensembleSize, int writeQuorumSize, int ackQuorumSize, BookieId bookieInEnsemble, List<BookieExpectedToContainSegmentInfo> bookieExpectedToContainSegmentInfoList, ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithMissingEntries, ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithUnavailableBookies, MultiCallback mcbForThisLedger) { this.ledgerInRange = ledgerInRange; this.ensembleSize = ensembleSize; this.writeQuorumSize = writeQuorumSize; this.ackQuorumSize = ackQuorumSize; this.bookieInEnsemble = bookieInEnsemble; this.bookieExpectedToContainSegmentInfoList = bookieExpectedToContainSegmentInfoList; this.ledgersWithMissingEntries = ledgersWithMissingEntries; this.ledgersWithUnavailableBookies = ledgersWithUnavailableBookies; this.mcbForThisLedger = mcbForThisLedger; } @Override public void accept(AvailabilityOfEntriesOfLedger availabilityOfEntriesOfLedger, Throwable listOfEntriesException) { if (listOfEntriesException != null) { if (BKException .getExceptionCode(listOfEntriesException) == BKException.Code.NoSuchLedgerExistsException) { if (LOG.isDebugEnabled()) { LOG.debug("Got NoSuchLedgerExistsException for ledger: {} from bookie: {}", ledgerInRange, bookieInEnsemble); } /* * in the case of NoSuchLedgerExistsException, it should be * considered as empty AvailabilityOfEntriesOfLedger. */ availabilityOfEntriesOfLedger = AvailabilityOfEntriesOfLedger.EMPTY_AVAILABILITYOFENTRIESOFLEDGER; } else { LOG.warn("Unable to GetListOfEntriesOfLedger for ledger: {} from: {}", ledgerInRange, bookieInEnsemble, listOfEntriesException); MissingEntriesInfoOfLedger unavailableBookiesInfoOfThisLedger = ledgersWithUnavailableBookies .get(ledgerInRange); if (unavailableBookiesInfoOfThisLedger == null) { ledgersWithUnavailableBookies.putIfAbsent(ledgerInRange, new MissingEntriesInfoOfLedger(ledgerInRange, ensembleSize, writeQuorumSize, ackQuorumSize, Collections.synchronizedList(new ArrayList<MissingEntriesInfo>()))); unavailableBookiesInfoOfThisLedger = ledgersWithUnavailableBookies.get(ledgerInRange); } List<MissingEntriesInfo> missingEntriesInfoList = unavailableBookiesInfoOfThisLedger.getMissingEntriesInfoList(); for (BookieExpectedToContainSegmentInfo bookieExpectedToContainSegmentInfo : bookieExpectedToContainSegmentInfoList) { missingEntriesInfoList.add( new MissingEntriesInfo(ledgerInRange, bookieExpectedToContainSegmentInfo.getSegmentEnsemble(), bookieInEnsemble, null)); /* * though GetListOfEntriesOfLedger has failed with * exception, mcbForThisLedger should be called back * with OK response, because we dont consider this as * fatal error in replicasCheck and dont want * replicasCheck to exit just because of this issue. So * instead maintain the state of * ledgersWithUnavailableBookies, so that replicascheck * will report these ledgers/bookies appropriately. */ mcbForThisLedger.processResult(BKException.Code.OK, null, null); } return; } } for (BookieExpectedToContainSegmentInfo bookieExpectedToContainSegmentInfo : bookieExpectedToContainSegmentInfoList) { final long startEntryIdOfSegment = bookieExpectedToContainSegmentInfo.getStartEntryIdOfSegment(); final long lastEntryIdOfSegment = bookieExpectedToContainSegmentInfo.getLastEntryIdOfSegment(); final BitSet entriesStripedToThisBookie = bookieExpectedToContainSegmentInfo .getEntriesOfSegmentStripedToThisBookie(); final Entry<Long, ? extends List<BookieId>> segmentEnsemble = bookieExpectedToContainSegmentInfo.getSegmentEnsemble(); final List<Long> unavailableEntriesList = availabilityOfEntriesOfLedger .getUnavailableEntries(startEntryIdOfSegment, lastEntryIdOfSegment, entriesStripedToThisBookie); if ((unavailableEntriesList != null) && (!unavailableEntriesList.isEmpty())) { MissingEntriesInfoOfLedger missingEntriesInfoOfThisLedger = ledgersWithMissingEntries .get(ledgerInRange); if (missingEntriesInfoOfThisLedger == null) { ledgersWithMissingEntries.putIfAbsent(ledgerInRange, new MissingEntriesInfoOfLedger(ledgerInRange, ensembleSize, writeQuorumSize, ackQuorumSize, Collections.synchronizedList(new ArrayList<MissingEntriesInfo>()))); missingEntriesInfoOfThisLedger = ledgersWithMissingEntries.get(ledgerInRange); } missingEntriesInfoOfThisLedger.getMissingEntriesInfoList().add( new MissingEntriesInfo(ledgerInRange, segmentEnsemble, bookieInEnsemble, unavailableEntriesList)); } /* * here though unavailableEntriesList is not empty, * mcbForThisLedger should be called back with OK response, * because we dont consider this as fatal error in replicasCheck * and dont want replicasCheck to exit just because of this * issue. So instead maintain the state of * missingEntriesInfoOfThisLedger, so that replicascheck will * report these ledgers/bookies/missingentries appropriately. */ mcbForThisLedger.processResult(BKException.Code.OK, null, null); } } } private static class ReplicasCheckFinalCallback implements AsyncCallback.VoidCallback { final AtomicInteger resultCode; final CountDownLatch replicasCheckLatch; private ReplicasCheckFinalCallback(AtomicInteger resultCode, CountDownLatch replicasCheckLatch) { this.resultCode = resultCode; this.replicasCheckLatch = replicasCheckLatch; } @Override public void processResult(int rc, String s, Object obj) { resultCode.set(rc); replicasCheckLatch.countDown(); } } private void reportLedgersWithMissingEntries( ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithMissingEntries) { StringBuilder errMessage = new StringBuilder(); HashMultiset<Long> missingEntries = HashMultiset.create(); int writeQuorumSize; int ackQuorumSize; for (Map.Entry<Long, MissingEntriesInfoOfLedger> missingEntriesInfoOfLedgerEntry : ledgersWithMissingEntries .entrySet()) { missingEntries.clear(); errMessage.setLength(0); long ledgerWithMissingEntries = missingEntriesInfoOfLedgerEntry.getKey(); MissingEntriesInfoOfLedger missingEntriesInfoOfLedger = missingEntriesInfoOfLedgerEntry.getValue(); List<MissingEntriesInfo> missingEntriesInfoList = missingEntriesInfoOfLedger.getMissingEntriesInfoList(); writeQuorumSize = missingEntriesInfoOfLedger.getWriteQuorumSize(); ackQuorumSize = missingEntriesInfoOfLedger.getAckQuorumSize(); errMessage.append("Ledger : " + ledgerWithMissingEntries + " has following missing entries : "); for (int listInd = 0; listInd < missingEntriesInfoList.size(); listInd++) { MissingEntriesInfo missingEntriesInfo = missingEntriesInfoList.get(listInd); List<Long> unavailableEntriesList = missingEntriesInfo.getUnavailableEntriesList(); Entry<Long, ? extends List<BookieId>> segmentEnsemble = missingEntriesInfo.getSegmentEnsemble(); missingEntries.addAll(unavailableEntriesList); errMessage.append("In segment starting at " + segmentEnsemble.getKey() + " with ensemble " + segmentEnsemble.getValue() + ", following entries " + unavailableEntriesList + " are missing in bookie: " + missingEntriesInfo.getBookieMissingEntries()); if (listInd < (missingEntriesInfoList.size() - 1)) { errMessage.append(", "); } } LOG.error(errMessage.toString()); Set<Multiset.Entry<Long>> missingEntriesSet = missingEntries.entrySet(); int maxNumOfMissingReplicas = 0; long entryWithMaxNumOfMissingReplicas = -1L; for (Multiset.Entry<Long> missingEntryWithCount : missingEntriesSet) { if (missingEntryWithCount.getCount() > maxNumOfMissingReplicas) { maxNumOfMissingReplicas = missingEntryWithCount.getCount(); entryWithMaxNumOfMissingReplicas = missingEntryWithCount.getElement(); } } int leastNumOfReplicasOfAnEntry = writeQuorumSize - maxNumOfMissingReplicas; if (leastNumOfReplicasOfAnEntry == 0) { numLedgersFoundHavingNoReplicaOfAnEntry.incrementAndGet(); LOG.error("Ledger : {} entryId : {} is missing all replicas", ledgerWithMissingEntries, entryWithMaxNumOfMissingReplicas); } else if (leastNumOfReplicasOfAnEntry < ackQuorumSize) { numLedgersFoundHavingLessThanAQReplicasOfAnEntry.incrementAndGet(); LOG.error("Ledger : {} entryId : {} is having: {} replicas, less than ackQuorum num of replicas : {}", ledgerWithMissingEntries, entryWithMaxNumOfMissingReplicas, leastNumOfReplicasOfAnEntry, ackQuorumSize); } else if (leastNumOfReplicasOfAnEntry < writeQuorumSize) { numLedgersFoundHavingLessThanWQReplicasOfAnEntry.incrementAndGet(); LOG.error("Ledger : {} entryId : {} is having: {} replicas, less than writeQuorum num of replicas : {}", ledgerWithMissingEntries, entryWithMaxNumOfMissingReplicas, leastNumOfReplicasOfAnEntry, writeQuorumSize); } } } private void reportLedgersWithUnavailableBookies( ConcurrentHashMap<Long, MissingEntriesInfoOfLedger> ledgersWithUnavailableBookies) { StringBuilder errMessage = new StringBuilder(); for (Map.Entry<Long, MissingEntriesInfoOfLedger> ledgerWithUnavailableBookiesInfo : ledgersWithUnavailableBookies.entrySet()) { errMessage.setLength(0); long ledgerWithUnavailableBookies = ledgerWithUnavailableBookiesInfo.getKey(); List<MissingEntriesInfo> missingBookiesInfoList = ledgerWithUnavailableBookiesInfo.getValue() .getMissingEntriesInfoList(); errMessage.append("Ledger : " + ledgerWithUnavailableBookies + " has following unavailable bookies : "); for (int listInd = 0; listInd < missingBookiesInfoList.size(); listInd++) { MissingEntriesInfo missingBookieInfo = missingBookiesInfoList.get(listInd); Entry<Long, ? extends List<BookieId>> segmentEnsemble = missingBookieInfo.getSegmentEnsemble(); errMessage.append("In segment starting at " + segmentEnsemble.getKey() + " with ensemble " + segmentEnsemble.getValue() + ", following bookie has not responded " + missingBookieInfo.getBookieMissingEntries()); if (listInd < (missingBookiesInfoList.size() - 1)) { errMessage.append(", "); } } LOG.error(errMessage.toString()); } } boolean checkUnderReplicationForReplicasCheck(long ledgerInRange, VoidCallback mcbForThisLedgerRange) { try { if (ledgerUnderreplicationManager.getLedgerUnreplicationInfo(ledgerInRange) == null) { return false; } /* * this ledger is marked underreplicated, so ignore it for * replicasCheck. */ if (LOG.isDebugEnabled()) { LOG.debug("Ledger: {} is marked underrreplicated, ignore this ledger for replicasCheck", ledgerInRange); } mcbForThisLedgerRange.processResult(BKException.Code.OK, null, null); return true; } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); return true; } catch (ReplicationException.UnavailableException une) { LOG.error("Got exception while trying to check if ledger: {} is underreplicated", ledgerInRange, une); mcbForThisLedgerRange.processResult(BKException.getExceptionCode(une), null, null); return true; } } }
288
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/ReplicationEnableCb.java
/* * * 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.bookkeeper.replication; import java.util.concurrent.CountDownLatch; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Callback which is getting notified when the replication process is enabled. */ public class ReplicationEnableCb implements GenericCallback<Void> { private static final Logger LOG = LoggerFactory .getLogger(ReplicationEnableCb.class); private final CountDownLatch latch = new CountDownLatch(1); @Override public void operationComplete(int rc, Void result) { latch.countDown(); if (LOG.isDebugEnabled()) { LOG.debug("Automatic ledger re-replication is enabled"); } } /** * This is a blocking call and causes the current thread to wait until the * replication process is enabled. * * @throws InterruptedException * interrupted while waiting */ public void await() throws InterruptedException { if (LOG.isDebugEnabled()) { LOG.debug("Automatic ledger re-replication is disabled. Hence waiting until its enabled!"); } latch.await(); } }
289
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/ReplicationException.java
/* * 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.bookkeeper.replication; import java.util.function.Function; import org.apache.zookeeper.KeeperException; /** * Exceptions for use within the replication service. */ public abstract class ReplicationException extends Exception { public static UnavailableException fromKeeperException(String message, KeeperException ke) { if (ke instanceof KeeperException.ConnectionLossException || ke instanceof KeeperException.SessionExpiredException) { return new NonRecoverableReplicationException(message, ke); } return new UnavailableException(message, ke); } public static final Function<Throwable, ReplicationException> EXCEPTION_HANDLER = cause -> { if (cause instanceof ReplicationException) { return (ReplicationException) cause; } else { return new UnavailableException(cause.getMessage(), cause); } }; protected ReplicationException(String message, Throwable cause) { super(message, cause); } protected ReplicationException(String message) { super(message); } /** * The replication service has become unavailable. */ public static class UnavailableException extends ReplicationException { private static final long serialVersionUID = 31872209L; public UnavailableException(String message, Throwable cause) { super(message, cause); } public UnavailableException(String message) { super(message); } } /** * The replication service encountered an error that requires service restart. */ public static class NonRecoverableReplicationException extends UnavailableException { private static final long serialVersionUID = 31872211L; public NonRecoverableReplicationException(String message, Throwable cause) { super(message, cause); } public NonRecoverableReplicationException(String message) { super(message); } } /** * Compatibility error. This version of the code, doesn't know how to * deal with the metadata it has found. */ public static class CompatibilityException extends ReplicationException { private static final long serialVersionUID = 98551903L; public CompatibilityException(String message, Throwable cause) { super(message, cause); } public CompatibilityException(String message) { super(message); } } /** * Exception while auditing bookie-ledgers. */ public static class BKAuditException extends ReplicationException { private static final long serialVersionUID = 95551905L; BKAuditException(String message, Throwable cause) { super(message, cause); } BKAuditException(String message) { super(message); } } }
290
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/ReplicationWorker.java
/* * 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.bookkeeper.replication; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_DEFER_LEDGER_LOCK_RELEASE_OF_FAILED_LEDGER; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_ENTRIES_UNABLE_TO_READ_FOR_REPLICATION; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_FULL_OR_PARTIAL_LEDGERS_REPLICATED; import static org.apache.bookkeeper.replication.ReplicationStats.NUM_NOT_ADHERING_PLACEMENT_LEDGERS_REPLICATED; import static org.apache.bookkeeper.replication.ReplicationStats.REPLICATE_EXCEPTION; import static org.apache.bookkeeper.replication.ReplicationStats.REPLICATION_WORKER_SCOPE; import static org.apache.bookkeeper.replication.ReplicationStats.REREPLICATE_OP; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Stopwatch; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.SortedMap; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import org.apache.bookkeeper.bookie.BookieThread; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BKException.BKNoSuchLedgerExistsOnMetadataServerException; import org.apache.bookkeeper.client.BKException.BKNotEnoughBookiesException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.client.EnsemblePlacementPolicy; import org.apache.bookkeeper.client.LedgerChecker; import org.apache.bookkeeper.client.LedgerFragment; import org.apache.bookkeeper.client.LedgerHandle; import org.apache.bookkeeper.client.api.LedgerMetadata; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback; import org.apache.bookkeeper.replication.ReplicationException.CompatibilityException; import org.apache.bookkeeper.replication.ReplicationException.UnavailableException; import org.apache.bookkeeper.stats.Counter; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.stats.annotations.StatsDoc; import org.apache.bookkeeper.versioning.Versioned; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ReplicationWorker will take the fragments one by one from * ZKLedgerUnderreplicationManager and replicates to it. */ @StatsDoc( name = REPLICATION_WORKER_SCOPE, help = "replication worker related stats" ) public class ReplicationWorker implements Runnable { private static final Logger LOG = LoggerFactory .getLogger(ReplicationWorker.class); private static final int REPLICATED_FAILED_LEDGERS_MAXSIZE = 2000; public static final int NUM_OF_EXPONENTIAL_BACKOFF_RETRIALS = 5; private final LedgerUnderreplicationManager underreplicationManager; private final ServerConfiguration conf; private volatile boolean workerRunning = false; private final BookKeeperAdmin admin; private final LedgerChecker ledgerChecker; private final BookKeeper bkc; private final boolean ownBkc; private final Thread workerThread; private final long rwRereplicateBackoffMs; private final long openLedgerRereplicationGracePeriod; private final Timer pendingReplicationTimer; private final long lockReleaseOfFailedLedgerGracePeriod; private final long baseBackoffForLockReleaseOfFailedLedger; private final BiConsumer<Long, Long> onReadEntryFailureCallback; private final LedgerManager ledgerManager; // Expose Stats private final StatsLogger statsLogger; @StatsDoc( name = REPLICATE_EXCEPTION, help = "replication related exceptions" ) private final StatsLogger exceptionLogger; @StatsDoc( name = REREPLICATE_OP, help = "operation stats of re-replicating ledgers" ) private final OpStatsLogger rereplicateOpStats; @StatsDoc( name = NUM_FULL_OR_PARTIAL_LEDGERS_REPLICATED, help = "the number of ledgers re-replicated" ) private final Counter numLedgersReplicated; @StatsDoc( name = NUM_DEFER_LEDGER_LOCK_RELEASE_OF_FAILED_LEDGER, help = "the number of defer-ledger-lock-releases of failed ledgers" ) private final Counter numDeferLedgerLockReleaseOfFailedLedger; @StatsDoc( name = NUM_ENTRIES_UNABLE_TO_READ_FOR_REPLICATION, help = "the number of entries ReplicationWorker unable to read" ) private final Counter numEntriesUnableToReadForReplication; @StatsDoc( name = NUM_NOT_ADHERING_PLACEMENT_LEDGERS_REPLICATED, help = "the number of not adhering placement policy ledgers re-replicated" ) private final Counter numNotAdheringPlacementLedgersReplicated; private final Map<String, Counter> exceptionCounters; final LoadingCache<Long, AtomicInteger> replicationFailedLedgers; final LoadingCache<Long, ConcurrentSkipListSet<Long>> unableToReadEntriesForReplication; /** * Replication worker for replicating the ledger fragments from * UnderReplicationManager to the targetBookie. This target bookie will be a * local bookie. * * @param conf * - configurations */ public ReplicationWorker(final ServerConfiguration conf) throws CompatibilityException, UnavailableException, InterruptedException, IOException { this(conf, NullStatsLogger.INSTANCE); } /** * Replication worker for replicating the ledger fragments from * UnderReplicationManager to the targetBookie. This target bookie will be a * local bookie. * * @param conf * - configurations * @param statsLogger * - stats logger */ public ReplicationWorker(final ServerConfiguration conf, StatsLogger statsLogger) throws CompatibilityException, UnavailableException, InterruptedException, IOException { this(conf, Auditor.createBookKeeperClient(conf), true, statsLogger); } ReplicationWorker(final ServerConfiguration conf, BookKeeper bkc, boolean ownBkc, StatsLogger statsLogger) throws CompatibilityException, InterruptedException, UnavailableException { this.conf = conf; this.bkc = bkc; this.ownBkc = ownBkc; this.underreplicationManager = bkc.getLedgerManagerFactory().newLedgerUnderreplicationManager(); this.ledgerManager = bkc.getLedgerManagerFactory().newLedgerManager(); this.admin = new BookKeeperAdmin(bkc, statsLogger, new ClientConfiguration(conf)); this.ledgerChecker = new LedgerChecker(bkc); this.workerThread = new BookieThread(this, "ReplicationWorker"); this.openLedgerRereplicationGracePeriod = conf .getOpenLedgerRereplicationGracePeriod(); this.lockReleaseOfFailedLedgerGracePeriod = conf.getLockReleaseOfFailedLedgerGracePeriod(); this.baseBackoffForLockReleaseOfFailedLedger = this.lockReleaseOfFailedLedgerGracePeriod / (long) (Math.pow(2, NUM_OF_EXPONENTIAL_BACKOFF_RETRIALS)); this.rwRereplicateBackoffMs = conf.getRwRereplicateBackoffMs(); this.pendingReplicationTimer = new Timer("PendingReplicationTimer"); this.replicationFailedLedgers = CacheBuilder.newBuilder().maximumSize(REPLICATED_FAILED_LEDGERS_MAXSIZE) .build(new CacheLoader<Long, AtomicInteger>() { @Override public AtomicInteger load(Long key) throws Exception { return new AtomicInteger(); } }); this.unableToReadEntriesForReplication = CacheBuilder.newBuilder() .maximumSize(REPLICATED_FAILED_LEDGERS_MAXSIZE) .build(new CacheLoader<Long, ConcurrentSkipListSet<Long>>() { @Override public ConcurrentSkipListSet<Long> load(Long key) throws Exception { return new ConcurrentSkipListSet<Long>(); } }); // Expose Stats this.statsLogger = statsLogger; this.exceptionLogger = statsLogger.scope(REPLICATE_EXCEPTION); this.rereplicateOpStats = this.statsLogger.getOpStatsLogger(REREPLICATE_OP); this.numLedgersReplicated = this.statsLogger.getCounter(NUM_FULL_OR_PARTIAL_LEDGERS_REPLICATED); this.numDeferLedgerLockReleaseOfFailedLedger = this.statsLogger .getCounter(NUM_DEFER_LEDGER_LOCK_RELEASE_OF_FAILED_LEDGER); this.numEntriesUnableToReadForReplication = this.statsLogger .getCounter(NUM_ENTRIES_UNABLE_TO_READ_FOR_REPLICATION); this.numNotAdheringPlacementLedgersReplicated = this.statsLogger .getCounter(NUM_NOT_ADHERING_PLACEMENT_LEDGERS_REPLICATED); this.exceptionCounters = new HashMap<String, Counter>(); this.onReadEntryFailureCallback = (ledgerid, entryid) -> { numEntriesUnableToReadForReplication.inc(); unableToReadEntriesForReplication.getUnchecked(ledgerid).add(entryid); }; } /** * Start the replication worker. */ public void start() { this.workerThread.start(); } @Override public void run() { workerRunning = true; while (workerRunning) { try { if (!rereplicate()) { LOG.warn("failed while replicating fragments"); waitBackOffTime(rwRereplicateBackoffMs); } } catch (InterruptedException e) { LOG.error("InterruptedException " + "while replicating fragments", e); shutdown(); Thread.currentThread().interrupt(); return; } catch (BKException e) { LOG.error("BKException while replicating fragments", e); waitBackOffTime(rwRereplicateBackoffMs); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("NonRecoverableReplicationException " + "while replicating fragments", nre); shutdown(); return; } catch (UnavailableException e) { LOG.error("UnavailableException " + "while replicating fragments", e); waitBackOffTime(rwRereplicateBackoffMs); if (Thread.currentThread().isInterrupted()) { LOG.error("Interrupted while replicating fragments"); shutdown(); return; } } } LOG.info("ReplicationWorker exited loop!"); } private static void waitBackOffTime(long backoffMs) { try { Thread.sleep(backoffMs); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } /** * Replicates the under replicated fragments from failed bookie ledger to * targetBookie. */ private boolean rereplicate() throws InterruptedException, BKException, UnavailableException { long ledgerIdToReplicate = underreplicationManager .getLedgerToRereplicate(); Stopwatch stopwatch = Stopwatch.createStarted(); boolean success = false; try { success = rereplicate(ledgerIdToReplicate); } finally { long latencyMillis = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS); if (success) { rereplicateOpStats.registerSuccessfulEvent(latencyMillis, TimeUnit.MILLISECONDS); } else { rereplicateOpStats.registerFailedEvent(latencyMillis, TimeUnit.MILLISECONDS); } } return success; } private void logBKExceptionAndReleaseLedger(BKException e, long ledgerIdToReplicate) throws UnavailableException { LOG.info("{} while" + " rereplicating ledger {}." + " Enough Bookies might not have available" + " So, no harm to continue", e.getClass().getSimpleName(), ledgerIdToReplicate); underreplicationManager .releaseUnderreplicatedLedger(ledgerIdToReplicate); getExceptionCounter(e.getClass().getSimpleName()).inc(); } private boolean tryReadingFaultyEntries(LedgerHandle lh, LedgerFragment ledgerFragment) { long ledgerId = lh.getId(); ConcurrentSkipListSet<Long> entriesUnableToReadForThisLedger = unableToReadEntriesForReplication .getIfPresent(ledgerId); if (entriesUnableToReadForThisLedger == null) { return true; } long firstEntryIdOfFragment = ledgerFragment.getFirstEntryId(); long lastEntryIdOfFragment = ledgerFragment.getLastKnownEntryId(); NavigableSet<Long> entriesOfThisFragmentUnableToRead = entriesUnableToReadForThisLedger .subSet(firstEntryIdOfFragment, true, lastEntryIdOfFragment, true); if (entriesOfThisFragmentUnableToRead.isEmpty()) { return true; } final CountDownLatch multiReadComplete = new CountDownLatch(1); final AtomicInteger numOfResponsesToWaitFor = new AtomicInteger(entriesOfThisFragmentUnableToRead.size()); final AtomicInteger returnRCValue = new AtomicInteger(BKException.Code.OK); for (long entryIdToRead : entriesOfThisFragmentUnableToRead) { if (multiReadComplete.getCount() == 0) { /* * if an asyncRead request had already failed then break the * loop. */ break; } lh.asyncReadEntries(entryIdToRead, entryIdToRead, (rc, ledHan, seq, ctx) -> { long thisEntryId = (Long) ctx; if (rc == BKException.Code.OK) { entriesUnableToReadForThisLedger.remove(thisEntryId); if (numOfResponsesToWaitFor.decrementAndGet() == 0) { multiReadComplete.countDown(); } } else { LOG.error("Received error: {} while trying to read entry: {} of ledger: {} in ReplicationWorker", rc, entryIdToRead, ledgerId); returnRCValue.compareAndSet(BKException.Code.OK, rc); /* * on receiving a failure error response, multiRead can be * marked completed, since there is not need to wait for * other responses. */ multiReadComplete.countDown(); } }, entryIdToRead); } try { multiReadComplete.await(); } catch (InterruptedException e) { LOG.error("Got interrupted exception while trying to read entries", e); Thread.currentThread().interrupt(); // set interrupt flag return false; } return (returnRCValue.get() == BKException.Code.OK); } private Set<LedgerFragment> getNeedRepairedPlacementNotAdheringFragments(LedgerHandle lh) { if (!conf.isRepairedPlacementPolicyNotAdheringBookieEnable()) { return Collections.emptySet(); } long ledgerId = lh.getId(); Set<LedgerFragment> placementNotAdheringFragments = new HashSet<>(); CompletableFuture<Versioned<LedgerMetadata>> future = ledgerManager.readLedgerMetadata( ledgerId).whenComplete((metadataVer, exception) -> { if (exception == null) { LedgerMetadata metadata = metadataVer.getValue(); int writeQuorumSize = metadata.getWriteQuorumSize(); int ackQuorumSize = metadata.getAckQuorumSize(); if (!metadata.isClosed()) { return; } Long curEntryId = null; EnsemblePlacementPolicy.PlacementPolicyAdherence previousSegmentAdheringToPlacementPolicy = null; for (Map.Entry<Long, ? extends List<BookieId>> entry : metadata.getAllEnsembles().entrySet()) { if (curEntryId != null) { if (EnsemblePlacementPolicy.PlacementPolicyAdherence.FAIL == previousSegmentAdheringToPlacementPolicy) { LedgerFragment ledgerFragment = new LedgerFragment(lh, curEntryId, entry.getKey() - 1, new HashSet<>()); ledgerFragment.setReplicateType(LedgerFragment.ReplicateType.DATA_NOT_ADHERING_PLACEMENT); placementNotAdheringFragments.add(ledgerFragment); } } previousSegmentAdheringToPlacementPolicy = admin.isEnsembleAdheringToPlacementPolicy(entry.getValue(), writeQuorumSize, ackQuorumSize); curEntryId = entry.getKey(); } if (curEntryId != null) { if (EnsemblePlacementPolicy.PlacementPolicyAdherence.FAIL == previousSegmentAdheringToPlacementPolicy) { long lastEntry = lh.getLedgerMetadata().getLastEntryId(); LedgerFragment ledgerFragment = new LedgerFragment(lh, curEntryId, lastEntry, new HashSet<>()); ledgerFragment.setReplicateType(LedgerFragment.ReplicateType.DATA_NOT_ADHERING_PLACEMENT); placementNotAdheringFragments.add(ledgerFragment); } } } else if (BKException.getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsOnMetadataServerException) { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring replication of already deleted ledger {}", ledgerId); } } else { LOG.warn("Unable to read the ledger: {} information", ledgerId); } }); try { FutureUtils.result(future); } catch (Exception e) { LOG.warn("Check ledger need repaired placement not adhering bookie failed", e); return Collections.emptySet(); } return placementNotAdheringFragments; } @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") private boolean rereplicate(long ledgerIdToReplicate) throws InterruptedException, BKException, UnavailableException { if (LOG.isDebugEnabled()) { LOG.debug("Going to replicate the fragments of the ledger: {}", ledgerIdToReplicate); } boolean deferLedgerLockRelease = false; try (LedgerHandle lh = admin.openLedgerNoRecovery(ledgerIdToReplicate)) { Set<LedgerFragment> fragments = getUnderreplicatedFragments(lh, conf.getAuditorLedgerVerificationPercentage()); if (LOG.isDebugEnabled()) { LOG.debug("Founds fragments {} for replication from ledger: {}", fragments, ledgerIdToReplicate); } boolean foundOpenFragments = false; long numFragsReplicated = 0; long numNotAdheringPlacementFragsReplicated = 0; for (LedgerFragment ledgerFragment : fragments) { if (!ledgerFragment.isClosed()) { foundOpenFragments = true; continue; } if (!tryReadingFaultyEntries(lh, ledgerFragment)) { LOG.error("Failed to read faulty entries, so giving up replicating ledgerFragment {}", ledgerFragment); continue; } try { admin.replicateLedgerFragment(lh, ledgerFragment, onReadEntryFailureCallback); numFragsReplicated++; if (ledgerFragment.getReplicateType() == LedgerFragment .ReplicateType.DATA_NOT_ADHERING_PLACEMENT) { numNotAdheringPlacementFragsReplicated++; } } catch (BKException.BKBookieHandleNotAvailableException e) { LOG.warn("BKBookieHandleNotAvailableException while replicating the fragment", e); } catch (BKException.BKLedgerRecoveryException e) { LOG.warn("BKLedgerRecoveryException while replicating the fragment", e); } catch (BKException.BKNotEnoughBookiesException e) { LOG.warn("BKNotEnoughBookiesException while replicating the fragment", e); } } if (numFragsReplicated > 0) { numLedgersReplicated.inc(); } if (numNotAdheringPlacementFragsReplicated > 0) { numNotAdheringPlacementLedgersReplicated.inc(); } if (foundOpenFragments || isLastSegmentOpenAndMissingBookies(lh)) { deferLedgerLockRelease = true; deferLedgerLockRelease(ledgerIdToReplicate); return false; } fragments = getUnderreplicatedFragments(lh, conf.getAuditorLedgerVerificationPercentage()); if (fragments.size() == 0) { LOG.info("Ledger replicated successfully. ledger id is: " + ledgerIdToReplicate); underreplicationManager.markLedgerReplicated(ledgerIdToReplicate); return true; } else { deferLedgerLockRelease = true; deferLedgerLockReleaseOfFailedLedger(ledgerIdToReplicate); numDeferLedgerLockReleaseOfFailedLedger.inc(); // Releasing the underReplication ledger lock and compete // for the replication again for the pending fragments return false; } } catch (BKNoSuchLedgerExistsOnMetadataServerException e) { // Ledger might have been deleted by user LOG.info("BKNoSuchLedgerExistsOnMetadataServerException while opening " + "ledger {} for replication. Other clients " + "might have deleted the ledger. " + "So, no harm to continue", ledgerIdToReplicate); underreplicationManager.markLedgerReplicated(ledgerIdToReplicate); getExceptionCounter("BKNoSuchLedgerExistsOnMetadataServerException").inc(); return false; } catch (BKNotEnoughBookiesException e) { logBKExceptionAndReleaseLedger(e, ledgerIdToReplicate); throw e; } catch (BKException e) { logBKExceptionAndReleaseLedger(e, ledgerIdToReplicate); return false; } finally { // we make sure we always release the underreplicated lock, unless we decided to defer it. If the lock has // already been released, this is a no-op if (!deferLedgerLockRelease) { try { underreplicationManager.releaseUnderreplicatedLedger(ledgerIdToReplicate); } catch (UnavailableException e) { LOG.error("UnavailableException while releasing the underreplicated lock for ledger {}:", ledgerIdToReplicate, e); shutdown(); } } } } /** * When checking the fragments of a ledger, there is a corner case * where if the last segment/ensemble is open, but nothing has been written to * some of the quorums in the ensemble, bookies can fail without any action being * taken. This is fine, until enough bookies fail to cause a quorum to become * unavailable, by which time the ledger is unrecoverable. * * <p>For example, if in a E3Q2, only 1 entry is written and the last bookie * in the ensemble fails, nothing has been written to it, so nothing needs to be * recovered. But if the second to last bookie fails, we've now lost quorum for * the second entry, so it's impossible to see if the second has been written or * not. * * <p>To avoid this situation, we need to check if bookies in the final open ensemble * are unavailable, and take action if so. The action to take is to close the ledger, * after a grace period as the writting client may replace the faulty bookie on its * own. * * <p>Missing bookies in closed ledgers are fine, as we know the last confirmed add, so * we can tell which entries are supposed to exist and rereplicate them if necessary. * * <p>Another corner case is that there are multiple ensembles in the ledger and the last * segment/ensemble is open, but nothing has been written to some quorums in the ensemble. * For the v2 protocol, this ledger's lastAddConfirm entry is the last segment/ensemble's `key - 2`, * not `key - 2`, the explanation please refer to: https://github.com/apache/bookkeeper/pull/3917. * If we treat the penultimate segment/ensemble as closed state, we will can't replicate * the last entry in the segment. So in this case, we should also check if the penultimate * segment/ensemble has missing bookies. */ private boolean isLastSegmentOpenAndMissingBookies(LedgerHandle lh) throws BKException { LedgerMetadata md = admin.getLedgerMetadata(lh); if (md.isClosed()) { return false; } SortedMap<Long, ? extends List<BookieId>> ensembles = admin.getLedgerMetadata(lh).getAllEnsembles(); List<BookieId> finalEnsemble = ensembles.get(ensembles.lastKey()); if (ensembles.size() > 1 && lh.getLastAddConfirmed() < ensembles.lastKey() - 1) { finalEnsemble = new ArrayList<>(finalEnsemble); finalEnsemble.addAll((new TreeMap<>(ensembles)).floorEntry(ensembles.lastKey() - 1).getValue()); } Collection<BookieId> available = admin.getAvailableBookies(); for (BookieId b : finalEnsemble) { if (!available.contains(b)) { if (LOG.isDebugEnabled()) { LOG.debug("Bookie {} is missing from the list of Available Bookies. ledger {}:ensemble {}.", b, lh.getId(), finalEnsemble); } return true; } } return false; } /** * Gets the under replicated fragments. */ private Set<LedgerFragment> getUnderreplicatedFragments(LedgerHandle lh, Long ledgerVerificationPercentage) throws InterruptedException { //The data loss fragments is first to repair. If a fragment is data_loss and not_adhering_placement //at the same time, we only fix data_loss in this time. After fix data_loss, the fragment is still //not_adhering_placement, Auditor will mark this ledger again. Set<LedgerFragment> underreplicatedFragments = new HashSet<>(); Set<LedgerFragment> dataLossFragments = getDataLossFragments(lh, ledgerVerificationPercentage); underreplicatedFragments.addAll(dataLossFragments); Set<LedgerFragment> notAdheringFragments = getNeedRepairedPlacementNotAdheringFragments(lh); for (LedgerFragment notAdheringFragment : notAdheringFragments) { if (!checkFragmentRepeat(underreplicatedFragments, notAdheringFragment)) { underreplicatedFragments.add(notAdheringFragment); } } return underreplicatedFragments; } private Set<LedgerFragment> getDataLossFragments(LedgerHandle lh, Long ledgerVerificationPercentage) throws InterruptedException { CheckerCallback checkerCb = new CheckerCallback(); ledgerChecker.checkLedger(lh, checkerCb, ledgerVerificationPercentage); return checkerCb.waitAndGetResult(); } private boolean checkFragmentRepeat(Set<LedgerFragment> fragments, LedgerFragment needChecked) { for (LedgerFragment fragment : fragments) { if (fragment.getLedgerId() == needChecked.getLedgerId() && fragment.getFirstEntryId() == needChecked.getFirstEntryId() && fragment.getLastKnownEntryId() == needChecked.getLastKnownEntryId()) { return true; } } return false; } void scheduleTaskWithDelay(TimerTask timerTask, long delayPeriod) { pendingReplicationTimer.schedule(timerTask, delayPeriod); } /** * Schedules a timer task for releasing the lock which will be scheduled * after open ledger fragment replication time. Ledger will be fenced if it * is still in open state when timer task fired. */ private void deferLedgerLockRelease(final long ledgerId) { long gracePeriod = this.openLedgerRereplicationGracePeriod; TimerTask timerTask = new TimerTask() { @Override public void run() { boolean isRecoveryOpen = false; LedgerHandle lh = null; try { lh = admin.openLedgerNoRecovery(ledgerId); if (isLastSegmentOpenAndMissingBookies(lh)) { // Need recovery open, close the old ledger handle. lh.close(); // Recovery open could result in client write failure. LOG.warn("Missing bookie(s) from last segment. Opening Ledger {} for Recovery.", ledgerId); lh = admin.openLedger(ledgerId); isRecoveryOpen = true; } if (!isRecoveryOpen){ Set<LedgerFragment> fragments = getUnderreplicatedFragments(lh, conf.getAuditorLedgerVerificationPercentage()); for (LedgerFragment fragment : fragments) { if (!fragment.isClosed()) { // Need recovery open, close the old ledger handle. lh.close(); // Recovery open could result in client write failure. LOG.warn("Open Fragment{}. Opening Ledger {} for Recovery.", fragment.getEnsemble(), ledgerId); lh = admin.openLedger(ledgerId); isRecoveryOpen = true; break; } } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.info("InterruptedException while fencing the ledger {}" + " for rereplication of postponed ledgers", ledgerId, e); } catch (BKNoSuchLedgerExistsOnMetadataServerException bknsle) { if (LOG.isDebugEnabled()) { LOG.debug("Ledger {} was deleted, safe to continue", ledgerId, bknsle); } } catch (BKException e) { LOG.error("BKException while fencing the ledger {}" + " for rereplication of postponed ledgers", ledgerId, e); } finally { try { if (lh != null) { lh.close(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.info("InterruptedException while closing ledger {}", ledgerId, e); } catch (BKException e) { // Lets go ahead and release the lock. Catch actual // exception in normal replication flow and take // action. LOG.warn("BKException while closing ledger {} ", ledgerId, e); } finally { try { underreplicationManager .releaseUnderreplicatedLedger(ledgerId); } catch (UnavailableException e) { LOG.error("UnavailableException while replicating fragments of ledger {}", ledgerId, e); shutdown(); } } } } }; scheduleTaskWithDelay(timerTask, gracePeriod); } /** * Schedules a timer task for releasing the lock. */ private void deferLedgerLockReleaseOfFailedLedger(final long ledgerId) { int numOfTimesFailedSoFar = replicationFailedLedgers.getUnchecked(ledgerId).getAndIncrement(); /* * for the first NUM_OF_EXPONENTIAL_BACKOFF_RETRIALS retrials do * exponential backoff, starting from * baseBackoffForLockReleaseOfFailedLedger */ long delayOfLedgerLockReleaseInMSecs = (numOfTimesFailedSoFar >= NUM_OF_EXPONENTIAL_BACKOFF_RETRIALS) ? this.lockReleaseOfFailedLedgerGracePeriod : this.baseBackoffForLockReleaseOfFailedLedger * (int) Math.pow(2, numOfTimesFailedSoFar); LOG.error( "ReplicationWorker failed to replicate Ledger : {} for {} number of times, " + "so deferring the ledger lock release by {} msecs", ledgerId, numOfTimesFailedSoFar, delayOfLedgerLockReleaseInMSecs); TimerTask timerTask = new TimerTask() { @Override public void run() { try { underreplicationManager.releaseUnderreplicatedLedger(ledgerId); } catch (UnavailableException e) { LOG.error("UnavailableException while replicating fragments of ledger {}", ledgerId, e); shutdown(); } } }; scheduleTaskWithDelay(timerTask, delayOfLedgerLockReleaseInMSecs); } /** * Stop the replication worker service. */ public void shutdown() { LOG.info("Shutting down replication worker"); synchronized (this) { if (!workerRunning) { return; } workerRunning = false; } LOG.info("Shutting down ReplicationWorker"); this.pendingReplicationTimer.cancel(); try { this.workerThread.interrupt(); this.workerThread.join(); } catch (InterruptedException e) { LOG.error("Interrupted during shutting down replication worker : ", e); Thread.currentThread().interrupt(); } if (ownBkc) { try { bkc.close(); } catch (InterruptedException e) { LOG.warn("Interrupted while closing the Bookie client", e); Thread.currentThread().interrupt(); } catch (BKException e) { LOG.warn("Exception while closing the Bookie client", e); } } try { underreplicationManager.close(); } catch (UnavailableException e) { LOG.warn("Exception while closing the " + "ZkLedgerUnderrepliationManager", e); } } /** * Gives the running status of ReplicationWorker. */ @VisibleForTesting public boolean isRunning() { return workerRunning && workerThread.isAlive(); } /** * Ledger checker call back. */ private static class CheckerCallback implements GenericCallback<Set<LedgerFragment>> { private Set<LedgerFragment> result = null; private CountDownLatch latch = new CountDownLatch(1); @Override public void operationComplete(int rc, Set<LedgerFragment> result) { this.result = result; latch.countDown(); } /** * Wait until operation complete call back comes and return the ledger * fragments set. */ Set<LedgerFragment> waitAndGetResult() throws InterruptedException { latch.await(); return result; } } private Counter getExceptionCounter(String name) { Counter counter = this.exceptionCounters.get(name); if (counter == null) { counter = this.exceptionLogger.getCounter(name); this.exceptionCounters.put(name, counter); } return counter; } }
291
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/AuditorPlacementPolicyCheckTask.java
/** * 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.bookkeeper.replication; import com.google.common.base.Stopwatch; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import lombok.Getter; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.client.EnsemblePlacementPolicy; import org.apache.bookkeeper.client.api.LedgerMetadata; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.bookkeeper.meta.UnderreplicatedLedger; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks; import org.apache.bookkeeper.versioning.Versioned; import org.apache.zookeeper.AsyncCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Getter public class AuditorPlacementPolicyCheckTask extends AuditorTask { private static final Logger LOG = LoggerFactory.getLogger(AuditorPlacementPolicyCheckTask.class); private final long underreplicatedLedgerRecoveryGracePeriod; private final AtomicInteger numOfLedgersFoundNotAdheringInPlacementPolicyCheck; private final AtomicInteger numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheck; private final AtomicInteger numOfClosedLedgersAuditedInPlacementPolicyCheck; private final AtomicInteger numOfURLedgersElapsedRecoveryGracePeriod; AuditorPlacementPolicyCheckTask(ServerConfiguration conf, AuditorStats auditorStats, BookKeeperAdmin admin, LedgerManager ledgerManager, LedgerUnderreplicationManager ledgerUnderreplicationManager, ShutdownTaskHandler shutdownTaskHandler, BiConsumer<AtomicBoolean, Throwable> hasAuditCheckTask) { super(conf, auditorStats, admin, ledgerManager, ledgerUnderreplicationManager, shutdownTaskHandler, hasAuditCheckTask); this.underreplicatedLedgerRecoveryGracePeriod = conf.getUnderreplicatedLedgerRecoveryGracePeriod(); this.numOfLedgersFoundNotAdheringInPlacementPolicyCheck = new AtomicInteger(0); this.numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheck = new AtomicInteger(0); this.numOfClosedLedgersAuditedInPlacementPolicyCheck = new AtomicInteger(0); this.numOfURLedgersElapsedRecoveryGracePeriod = new AtomicInteger(0); } @Override protected void runTask() { if (hasBookieCheckTask()) { LOG.info("Audit bookie task already scheduled; skipping periodic placement policy check task"); auditorStats.getNumSkippingCheckTaskTimes().inc(); return; } try { if (!isLedgerReplicationEnabled()) { LOG.info("Ledger replication disabled, skipping placementPolicyCheck"); return; } Stopwatch stopwatch = Stopwatch.createStarted(); LOG.info("Starting PlacementPolicyCheck"); placementPolicyCheck(); long placementPolicyCheckDuration = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS); int numOfLedgersFoundNotAdheringInPlacementPolicyCheckValue = numOfLedgersFoundNotAdheringInPlacementPolicyCheck.get(); int numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheckValue = numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheck.get(); int numOfClosedLedgersAuditedInPlacementPolicyCheckValue = numOfClosedLedgersAuditedInPlacementPolicyCheck.get(); int numOfURLedgersElapsedRecoveryGracePeriodValue = numOfURLedgersElapsedRecoveryGracePeriod.get(); LOG.info( "Completed placementPolicyCheck in {} milliSeconds." + " numOfClosedLedgersAuditedInPlacementPolicyCheck {}" + " numOfLedgersNotAdheringToPlacementPolicy {}" + " numOfLedgersSoftlyAdheringToPlacementPolicy {}" + " numOfURLedgersElapsedRecoveryGracePeriod {}", placementPolicyCheckDuration, numOfClosedLedgersAuditedInPlacementPolicyCheckValue, numOfLedgersFoundNotAdheringInPlacementPolicyCheckValue, numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheckValue, numOfURLedgersElapsedRecoveryGracePeriodValue); auditorStats.getLedgersNotAdheringToPlacementPolicyGuageValue() .set(numOfLedgersFoundNotAdheringInPlacementPolicyCheckValue); auditorStats.getLedgersSoftlyAdheringToPlacementPolicyGuageValue() .set(numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheckValue); auditorStats.getNumOfURLedgersElapsedRecoveryGracePeriodGuageValue() .set(numOfURLedgersElapsedRecoveryGracePeriodValue); auditorStats.getPlacementPolicyCheckTime().registerSuccessfulEvent(placementPolicyCheckDuration, TimeUnit.MILLISECONDS); } catch (ReplicationException.BKAuditException e) { int numOfLedgersFoundInPlacementPolicyCheckValue = numOfLedgersFoundNotAdheringInPlacementPolicyCheck.get(); if (numOfLedgersFoundInPlacementPolicyCheckValue > 0) { /* * Though there is BKAuditException while doing * placementPolicyCheck, it found few ledgers not * adhering to placement policy. So reporting it. */ auditorStats.getLedgersNotAdheringToPlacementPolicyGuageValue() .set(numOfLedgersFoundInPlacementPolicyCheckValue); } int numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheckValue = numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheck.get(); if (numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheckValue > 0) { /* * Though there is BKAuditException while doing * placementPolicyCheck, it found few ledgers softly * adhering to placement policy. So reporting it. */ auditorStats.getLedgersSoftlyAdheringToPlacementPolicyGuageValue() .set(numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheckValue); } int numOfURLedgersElapsedRecoveryGracePeriodValue = numOfURLedgersElapsedRecoveryGracePeriod.get(); if (numOfURLedgersElapsedRecoveryGracePeriodValue > 0) { /* * Though there is BKAuditException while doing * placementPolicyCheck, it found few urledgers have * elapsed recovery graceperiod. So reporting it. */ auditorStats.getNumOfURLedgersElapsedRecoveryGracePeriodGuageValue() .set(numOfURLedgersElapsedRecoveryGracePeriodValue); } LOG.error( "BKAuditException running periodic placementPolicy check." + "numOfLedgersNotAdheringToPlacementPolicy {}, " + "numOfLedgersSoftlyAdheringToPlacementPolicy {}," + "numOfURLedgersElapsedRecoveryGracePeriod {}", numOfLedgersFoundInPlacementPolicyCheckValue, numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheckValue, numOfURLedgersElapsedRecoveryGracePeriodValue, e); } catch (ReplicationException.UnavailableException ue) { LOG.error("Underreplication manager unavailable running periodic check", ue); } } @Override public void shutdown() { } void placementPolicyCheck() throws ReplicationException.BKAuditException { final CountDownLatch placementPolicyCheckLatch = new CountDownLatch(1); numOfLedgersFoundNotAdheringInPlacementPolicyCheck.set(0); numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheck.set(0); numOfClosedLedgersAuditedInPlacementPolicyCheck.set(0); numOfURLedgersElapsedRecoveryGracePeriod.set(0); if (this.underreplicatedLedgerRecoveryGracePeriod > 0) { Iterator<UnderreplicatedLedger> underreplicatedLedgersInfo = ledgerUnderreplicationManager .listLedgersToRereplicate(null); List<Long> urLedgersElapsedRecoveryGracePeriod = new ArrayList<Long>(); while (underreplicatedLedgersInfo.hasNext()) { UnderreplicatedLedger underreplicatedLedger = underreplicatedLedgersInfo.next(); long underreplicatedLedgerMarkTimeInMilSecs = underreplicatedLedger.getCtime(); if (underreplicatedLedgerMarkTimeInMilSecs != UnderreplicatedLedger.UNASSIGNED_CTIME) { long elapsedTimeInSecs = (System.currentTimeMillis() - underreplicatedLedgerMarkTimeInMilSecs) / 1000; if (elapsedTimeInSecs > this.underreplicatedLedgerRecoveryGracePeriod) { urLedgersElapsedRecoveryGracePeriod.add(underreplicatedLedger.getLedgerId()); numOfURLedgersElapsedRecoveryGracePeriod.incrementAndGet(); } } } if (urLedgersElapsedRecoveryGracePeriod.isEmpty()) { LOG.info("No Underreplicated ledger has elapsed recovery graceperiod: {}", urLedgersElapsedRecoveryGracePeriod); } else { LOG.error("Following Underreplicated ledgers have elapsed recovery graceperiod: {}", urLedgersElapsedRecoveryGracePeriod); } } BookkeeperInternalCallbacks.Processor<Long> ledgerProcessor = new BookkeeperInternalCallbacks.Processor<Long>() { @Override public void process(Long ledgerId, AsyncCallback.VoidCallback iterCallback) { ledgerManager.readLedgerMetadata(ledgerId).whenComplete((metadataVer, exception) -> { if (exception == null) { doPlacementPolicyCheck(ledgerId, iterCallback, metadataVer); } else if (BKException.getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsOnMetadataServerException) { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring replication of already deleted ledger {}", ledgerId); } iterCallback.processResult(BKException.Code.OK, null, null); } else { LOG.warn("Unable to read the ledger: {} information", ledgerId); iterCallback.processResult(BKException.getExceptionCode(exception), null, null); } }); } }; // Reading the result after processing all the ledgers final List<Integer> resultCode = new ArrayList<Integer>(1); ledgerManager.asyncProcessLedgers(ledgerProcessor, new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String s, Object obj) { resultCode.add(rc); placementPolicyCheckLatch.countDown(); } }, null, BKException.Code.OK, BKException.Code.ReadException); try { placementPolicyCheckLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ReplicationException.BKAuditException("Exception while doing placementPolicy check", e); } if (!resultCode.contains(BKException.Code.OK)) { throw new ReplicationException.BKAuditException("Exception while doing placementPolicy check", BKException.create(resultCode.get(0))); } try { ledgerUnderreplicationManager.setPlacementPolicyCheckCTime(System.currentTimeMillis()); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); } catch (ReplicationException.UnavailableException ue) { LOG.error("Got exception while trying to set PlacementPolicyCheckCTime", ue); } } void doPlacementPolicyCheck(Long ledgerId, AsyncCallback.VoidCallback iterCallback, Versioned<LedgerMetadata> metadataVer) { LedgerMetadata metadata = metadataVer.getValue(); int writeQuorumSize = metadata.getWriteQuorumSize(); int ackQuorumSize = metadata.getAckQuorumSize(); if (metadata.isClosed()) { boolean foundSegmentNotAdheringToPlacementPolicy = false; boolean foundSegmentSoftlyAdheringToPlacementPolicy = false; for (Map.Entry<Long, ? extends List<BookieId>> ensemble : metadata .getAllEnsembles().entrySet()) { long startEntryIdOfSegment = ensemble.getKey(); List<BookieId> ensembleOfSegment = ensemble.getValue(); EnsemblePlacementPolicy.PlacementPolicyAdherence segmentAdheringToPlacementPolicy = admin .isEnsembleAdheringToPlacementPolicy(ensembleOfSegment, writeQuorumSize, ackQuorumSize); if (segmentAdheringToPlacementPolicy == EnsemblePlacementPolicy.PlacementPolicyAdherence.FAIL) { foundSegmentNotAdheringToPlacementPolicy = true; LOG.warn( "For ledger: {}, Segment starting at entry: {}, with ensemble: {} having " + "writeQuorumSize: {} and ackQuorumSize: {} is not adhering to " + "EnsemblePlacementPolicy", ledgerId, startEntryIdOfSegment, ensembleOfSegment, writeQuorumSize, ackQuorumSize); } else if (segmentAdheringToPlacementPolicy == EnsemblePlacementPolicy.PlacementPolicyAdherence.MEETS_SOFT) { foundSegmentSoftlyAdheringToPlacementPolicy = true; if (LOG.isDebugEnabled()) { LOG.debug( "For ledger: {}, Segment starting at entry: {}, with ensemble: {}" + " having writeQuorumSize: {} and ackQuorumSize: {} is" + " softly adhering to EnsemblePlacementPolicy", ledgerId, startEntryIdOfSegment, ensembleOfSegment, writeQuorumSize, ackQuorumSize); } } } if (foundSegmentNotAdheringToPlacementPolicy) { numOfLedgersFoundNotAdheringInPlacementPolicyCheck.incrementAndGet(); //If user enable repaired, mark this ledger to under replication manager. if (conf.isRepairedPlacementPolicyNotAdheringBookieEnable()) { ledgerUnderreplicationManager.markLedgerUnderreplicatedAsync(ledgerId, Collections.emptyList()).whenComplete((res, e) -> { if (e != null) { LOG.error("For ledger: {}, the placement policy not adhering bookie " + "storage, mark it to under replication manager failed.", ledgerId, e); return; } if (LOG.isDebugEnabled()) { LOG.debug("For ledger: {}, the placement policy not adhering bookie" + " storage, mark it to under replication manager", ledgerId); } }); } } else if (foundSegmentSoftlyAdheringToPlacementPolicy) { numOfLedgersFoundSoftlyAdheringInPlacementPolicyCheck .incrementAndGet(); } numOfClosedLedgersAuditedInPlacementPolicyCheck.incrementAndGet(); } else { if (LOG.isDebugEnabled()) { LOG.debug("Ledger: {} is not yet closed, so skipping the placementPolicy" + "check analysis for now", ledgerId); } } iterCallback.processResult(BKException.Code.OK, null, null); } }
292
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/ReplicationStats.java
/* * * 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.bookkeeper.replication; /** * Replication statistics. */ public interface ReplicationStats { String REPLICATION_SCOPE = "replication"; String AUDITOR_SCOPE = "auditor"; String ELECTION_ATTEMPTS = "election_attempts"; String NUM_UNDER_REPLICATED_LEDGERS = "NUM_UNDER_REPLICATED_LEDGERS"; String UNDER_REPLICATED_LEDGERS_TOTAL_SIZE = "UNDER_REPLICATED_LEDGERS_TOTAL_SIZE"; String URL_PUBLISH_TIME_FOR_LOST_BOOKIE = "URL_PUBLISH_TIME_FOR_LOST_BOOKIE"; String BOOKIE_TO_LEDGERS_MAP_CREATION_TIME = "BOOKIE_TO_LEDGERS_MAP_CREATION_TIME"; String CHECK_ALL_LEDGERS_TIME = "CHECK_ALL_LEDGERS_TIME"; String PLACEMENT_POLICY_CHECK_TIME = "PLACEMENT_POLICY_CHECK_TIME"; String REPLICAS_CHECK_TIME = "REPLICAS_CHECK_TIME"; String AUDIT_BOOKIES_TIME = "AUDIT_BOOKIES_TIME"; String NUM_FRAGMENTS_PER_LEDGER = "NUM_FRAGMENTS_PER_LEDGER"; String NUM_BOOKIES_PER_LEDGER = "NUM_BOOKIES_PER_LEDGER"; String NUM_LEDGERS_CHECKED = "NUM_LEDGERS_CHECKED"; String NUM_BOOKIE_AUDITS_DELAYED = "NUM_BOOKIE_AUDITS_DELAYED"; String NUM_DELAYED_BOOKIE_AUDITS_DELAYES_CANCELLED = "NUM_DELAYED_BOOKIE_AUDITS_CANCELLED"; String NUM_LEDGERS_NOT_ADHERING_TO_PLACEMENT_POLICY = "NUM_LEDGERS_NOT_ADHERING_TO_PLACEMENT_POLICY"; String NUM_LEDGERS_SOFTLY_ADHERING_TO_PLACEMENT_POLICY = "NUM_LEDGERS_SOFTLY_ADHERING_TO_PLACEMENT_POLICY"; String NUM_UNDERREPLICATED_LEDGERS_ELAPSED_RECOVERY_GRACE_PERIOD = "NUM_UNDERREPLICATED_LEDGERS_ELAPSED_RECOVERY_GRACE_PERIOD"; String NUM_LEDGERS_HAVING_NO_REPLICA_OF_AN_ENTRY = "NUM_LEDGERS_HAVING_NO_REPLICA_OF_AN_ENTRY"; String NUM_LEDGERS_HAVING_LESS_THAN_AQ_REPLICAS_OF_AN_ENTRY = "NUM_LEDGERS_HAVING_LESS_THAN_AQ_REPLICAS_OF_AN_ENTRY"; String NUM_LEDGERS_HAVING_LESS_THAN_WQ_REPLICAS_OF_AN_ENTRY = "NUM_LEDGERS_HAVING_LESS_THAN_WQ_REPLICAS_OF_AN_ENTRY"; String REPLICATION_WORKER_SCOPE = "replication_worker"; String REREPLICATE_OP = "rereplicate"; String NUM_FULL_OR_PARTIAL_LEDGERS_REPLICATED = "NUM_FULL_OR_PARTIAL_LEDGERS_REPLICATED"; String NUM_ENTRIES_READ = "NUM_ENTRIES_READ"; String NUM_BYTES_READ = "NUM_BYTES_READ"; String NUM_ENTRIES_WRITTEN = "NUM_ENTRIES_WRITTEN"; String NUM_BYTES_WRITTEN = "NUM_BYTES_WRITTEN"; String READ_DATA_LATENCY = "READ_DATA_LATENCY"; String WRITE_DATA_LATENCY = "WRITE_DATA_LATENCY"; String REPLICATE_EXCEPTION = "exceptions"; String NUM_DEFER_LEDGER_LOCK_RELEASE_OF_FAILED_LEDGER = "NUM_DEFER_LEDGER_LOCK_RELEASE_OF_FAILED_LEDGER"; String NUM_ENTRIES_UNABLE_TO_READ_FOR_REPLICATION = "NUM_ENTRIES_UNABLE_TO_READ_FOR_REPLICATION"; String NUM_NOT_ADHERING_PLACEMENT_LEDGERS_REPLICATED = "NUM_NOT_ADHERING_PLACEMENT_LEDGERS_REPLICATED"; String NUM_SKIPPING_CHECK_TASK_TIMES = "NUM_SKIPPING_CHECK_TASK_TIMES"; }
293
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/AuditorElector.java
/* * * 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.bookkeeper.replication; import static org.apache.bookkeeper.replication.ReplicationStats.AUDITOR_SCOPE; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerAuditorManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.replication.ReplicationException.UnavailableException; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.stats.annotations.StatsDoc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Performing auditor election using Apache ZooKeeper. Using ZooKeeper as a * coordination service, when a bookie bids for auditor, it creates an ephemeral * sequential file (znode) on ZooKeeper and considered as their vote. Vote * format is 'V_sequencenumber'. Election will be done by comparing the * ephemeral sequential numbers and the bookie which has created the least znode * will be elected as Auditor. All the other bookies will be watching on their * predecessor znode according to the ephemeral sequence numbers. */ @StatsDoc( name = AUDITOR_SCOPE, help = "Auditor related stats" ) public class AuditorElector { private static final Logger LOG = LoggerFactory .getLogger(AuditorElector.class); private final String bookieId; private final ServerConfiguration conf; private final BookKeeper bkc; private final boolean ownBkc; private final ExecutorService executor; private final LedgerAuditorManager ledgerAuditorManager; Auditor auditor; private AtomicBoolean running = new AtomicBoolean(false); private final StatsLogger statsLogger; @VisibleForTesting public AuditorElector(final String bookieId, ServerConfiguration conf) throws UnavailableException { this( bookieId, conf, Auditor.createBookKeeperClientThrowUnavailableException(conf), true); } /** * AuditorElector for performing the auditor election. * * @param bookieId * - bookie identifier, comprises HostAddress:Port * @param conf * - configuration * @param bkc * - bookkeeper instance * @throws UnavailableException * throws unavailable exception while initializing the elector */ public AuditorElector(final String bookieId, ServerConfiguration conf, BookKeeper bkc, boolean ownBkc) throws UnavailableException { this(bookieId, conf, bkc, NullStatsLogger.INSTANCE, ownBkc); } /** * AuditorElector for performing the auditor election. * * @param bookieId * - bookie identifier, comprises HostAddress:Port * @param conf * - configuration * @param bkc * - bookkeeper instance * @param statsLogger * - stats logger * @throws UnavailableException * throws unavailable exception while initializing the elector */ public AuditorElector(final String bookieId, ServerConfiguration conf, BookKeeper bkc, StatsLogger statsLogger, boolean ownBkc) throws UnavailableException { this.bookieId = bookieId; this.conf = conf; this.bkc = bkc; this.ownBkc = ownBkc; this.statsLogger = statsLogger; try { this.ledgerAuditorManager = bkc.getLedgerManagerFactory().newLedgerAuditorManager(); } catch (Exception e) { throw new UnavailableException("Failed to instantiate the ledger auditor manager", e); } executor = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "AuditorElector-" + bookieId); } }); } public Future<?> start() { running.set(true); return submitElectionTask(); } /** * Run cleanup operations for the auditor elector. */ private void submitShutdownTask() { executor.submit(new Runnable() { @Override public void run() { if (!running.compareAndSet(true, false)) { return; } try { ledgerAuditorManager.close(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.warn("InterruptedException while closing ledger auditor manager", ie); } catch (Exception ke) { LOG.error("Exception while closing ledger auditor manager", ke); } } }); } /** * Performing the auditor election using the ZooKeeper ephemeral sequential * znode. The bookie which has created the least sequential will be elect as * Auditor. */ @VisibleForTesting Future<?> submitElectionTask() { Runnable r = new Runnable() { @Override public void run() { if (!running.get()) { return; } try { ledgerAuditorManager.tryToBecomeAuditor(bookieId, e -> handleAuditorEvent(e)); auditor = new Auditor(bookieId, conf, bkc, false, statsLogger); auditor.start(); } catch (InterruptedException e) { LOG.error("Interrupted while performing auditor election", e); Thread.currentThread().interrupt(); submitShutdownTask(); } catch (Exception e) { LOG.error("Exception while performing auditor election", e); submitShutdownTask(); } } }; try { return executor.submit(r); } catch (RejectedExecutionException e) { if (LOG.isDebugEnabled()) { LOG.debug("Executor was already closed"); } return CompletableFuture.completedFuture(null); } } private void handleAuditorEvent(LedgerAuditorManager.AuditorEvent e) { switch (e) { case SessionLost: LOG.error("Lost ZK connection, shutting down"); submitShutdownTask(); break; case VoteWasDeleted: submitElectionTask(); break; } } @VisibleForTesting Auditor getAuditor() { return auditor; } public BookieId getCurrentAuditor() throws IOException, InterruptedException { return ledgerAuditorManager.getCurrentAuditor(); } /** * Shutting down AuditorElector. */ public void shutdown() throws InterruptedException { synchronized (this) { if (executor.isShutdown()) { return; } // close auditor manager submitShutdownTask(); executor.shutdown(); } if (auditor != null) { auditor.shutdown(); auditor = null; } if (ownBkc) { try { bkc.close(); } catch (BKException e) { LOG.warn("Failed to close bookkeeper client", e); } } } /** * If current bookie is running as auditor, return the status of the * auditor. Otherwise return the status of elector. * * @return */ public boolean isRunning() { if (auditor != null) { return auditor.isRunning(); } return running.get(); } @Override public String toString() { return "AuditorElector for " + bookieId; } }
294
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/Auditor.java
/* * * 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.bookkeeper.replication; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.SettableFuture; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerManagerFactory; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback; import org.apache.bookkeeper.replication.ReplicationException.BKAuditException; import org.apache.bookkeeper.replication.ReplicationException.CompatibilityException; import org.apache.bookkeeper.replication.ReplicationException.UnavailableException; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.commons.collections4.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Auditor is a single entity in the entire Bookie cluster and will be watching * all the bookies under 'ledgerrootpath/available' zkpath. When any of the * bookie failed or disconnected from zk, he will start initiating the * re-replication activities by keeping all the corresponding ledgers of the * failed bookie as underreplicated znode in zk. * * <p>TODO: eliminate the direct usage of zookeeper here {@link https://github.com/apache/bookkeeper/issues/1332} */ public class Auditor implements AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(Auditor.class); private final ServerConfiguration conf; private final BookKeeper bkc; private final boolean ownBkc; private final BookKeeperAdmin admin; private final boolean ownAdmin; private BookieLedgerIndexer bookieLedgerIndexer; private LedgerManager ledgerManager; private LedgerUnderreplicationManager ledgerUnderreplicationManager; private final ScheduledExecutorService executor; private List<String> knownBookies = new ArrayList<String>(); private final String bookieIdentifier; protected volatile Future<?> auditTask; private final Set<String> bookiesToBeAudited = Sets.newHashSet(); private volatile int lostBookieRecoveryDelayBeforeChange; protected AuditorBookieCheckTask auditorBookieCheckTask; protected AuditorTask auditorCheckAllLedgersTask; protected AuditorTask auditorPlacementPolicyCheckTask; protected AuditorTask auditorReplicasCheckTask; private final List<AuditorTask> allAuditorTasks = Lists.newArrayList(); private final AuditorStats auditorStats; static BookKeeper createBookKeeperClient(ServerConfiguration conf) throws InterruptedException, IOException { return createBookKeeperClient(conf, NullStatsLogger.INSTANCE); } static BookKeeper createBookKeeperClient(ServerConfiguration conf, StatsLogger statsLogger) throws InterruptedException, IOException { ClientConfiguration clientConfiguration = new ClientConfiguration(conf); clientConfiguration.setClientRole(ClientConfiguration.CLIENT_ROLE_SYSTEM); try { return BookKeeper.forConfig(clientConfiguration).statsLogger(statsLogger).build(); } catch (BKException e) { throw new IOException("Failed to create bookkeeper client", e); } } static BookKeeper createBookKeeperClientThrowUnavailableException(ServerConfiguration conf) throws UnavailableException { try { return createBookKeeperClient(conf); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new UnavailableException("Failed to create bookkeeper client", e); } catch (IOException e) { throw new UnavailableException("Failed to create bookkeeper client", e); } } public Auditor(final String bookieIdentifier, ServerConfiguration conf, StatsLogger statsLogger) throws UnavailableException { this( bookieIdentifier, conf, createBookKeeperClientThrowUnavailableException(conf), true, statsLogger); } public Auditor(final String bookieIdentifier, ServerConfiguration conf, BookKeeper bkc, boolean ownBkc, StatsLogger statsLogger) throws UnavailableException { this(bookieIdentifier, conf, bkc, ownBkc, new BookKeeperAdmin(bkc, statsLogger, new ClientConfiguration(conf)), true, statsLogger); } public Auditor(final String bookieIdentifier, ServerConfiguration conf, BookKeeper bkc, boolean ownBkc, BookKeeperAdmin admin, boolean ownAdmin, StatsLogger statsLogger) throws UnavailableException { this.conf = conf; this.bookieIdentifier = bookieIdentifier; this.auditorStats = new AuditorStats(statsLogger); this.bkc = bkc; this.ownBkc = ownBkc; this.admin = admin; this.ownAdmin = ownAdmin; initialize(conf, bkc); AuditorTask.ShutdownTaskHandler shutdownTaskHandler = this::submitShutdownTask; BiConsumer<Void, Throwable> submitBookieCheckTask = (ignore, throwable) -> this.submitBookieCheckTask(); BiConsumer<AtomicBoolean, Throwable> hasAuditCheckTask = (flag, throwable) -> flag.set(auditTask != null); this.auditorBookieCheckTask = new AuditorBookieCheckTask( conf, auditorStats, admin, ledgerManager, ledgerUnderreplicationManager, shutdownTaskHandler, bookieLedgerIndexer, hasAuditCheckTask, submitBookieCheckTask); allAuditorTasks.add(auditorBookieCheckTask); this.auditorCheckAllLedgersTask = new AuditorCheckAllLedgersTask( conf, auditorStats, admin, ledgerManager, ledgerUnderreplicationManager, shutdownTaskHandler, hasAuditCheckTask); allAuditorTasks.add(auditorCheckAllLedgersTask); this.auditorPlacementPolicyCheckTask = new AuditorPlacementPolicyCheckTask( conf, auditorStats, admin, ledgerManager, ledgerUnderreplicationManager, shutdownTaskHandler, hasAuditCheckTask); allAuditorTasks.add(auditorPlacementPolicyCheckTask); this.auditorReplicasCheckTask = new AuditorReplicasCheckTask( conf, auditorStats, admin, ledgerManager, ledgerUnderreplicationManager, shutdownTaskHandler, hasAuditCheckTask); allAuditorTasks.add(auditorReplicasCheckTask); executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "AuditorBookie-" + bookieIdentifier); t.setDaemon(true); return t; } }); } private void initialize(ServerConfiguration conf, BookKeeper bkc) throws UnavailableException { try { LedgerManagerFactory ledgerManagerFactory = bkc.getLedgerManagerFactory(); ledgerManager = ledgerManagerFactory.newLedgerManager(); this.bookieLedgerIndexer = new BookieLedgerIndexer(ledgerManager); this.ledgerUnderreplicationManager = ledgerManagerFactory .newLedgerUnderreplicationManager(); LOG.info("AuthProvider used by the Auditor is {}", admin.getConf().getClientAuthProviderFactoryClass()); if (this.ledgerUnderreplicationManager .initializeLostBookieRecoveryDelay(conf.getLostBookieRecoveryDelay())) { LOG.info("Initializing lostBookieRecoveryDelay zNode to the conf value: {}", conf.getLostBookieRecoveryDelay()); } else { LOG.info("Valid lostBookieRecoveryDelay zNode is available, so not creating " + "lostBookieRecoveryDelay zNode as part of Auditor initialization "); } lostBookieRecoveryDelayBeforeChange = this.ledgerUnderreplicationManager.getLostBookieRecoveryDelay(); } catch (CompatibilityException ce) { throw new UnavailableException( "CompatibilityException while initializing Auditor", ce); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new UnavailableException( "Interrupted while initializing Auditor", ie); } } private void submitShutdownTask() { synchronized (this) { LOG.info("Executing submitShutdownTask"); if (executor.isShutdown()) { LOG.info("executor is already shutdown"); return; } executor.submit(() -> { synchronized (Auditor.this) { LOG.info("Shutting down Auditor's Executor"); executor.shutdown(); } }); } } @VisibleForTesting synchronized Future<?> submitAuditTask() { if (executor.isShutdown()) { SettableFuture<Void> f = SettableFuture.<Void>create(); f.setException(new BKAuditException("Auditor shutting down")); return f; } return executor.submit(() -> { try { waitIfLedgerReplicationDisabled(); int lostBookieRecoveryDelay = Auditor.this.ledgerUnderreplicationManager .getLostBookieRecoveryDelay(); List<String> availableBookies = getAvailableBookies(); // casting to String, as knownBookies and availableBookies // contains only String values // find new bookies(if any) and update the known bookie list Collection<String> newBookies = CollectionUtils.subtract( availableBookies, knownBookies); knownBookies.addAll(newBookies); if (!bookiesToBeAudited.isEmpty() && knownBookies.containsAll(bookiesToBeAudited)) { // the bookie, which went down earlier and had an audit scheduled for, // has come up. So let us stop tracking it and cancel the audit. Since // we allow delaying of audit when there is only one failed bookie, // bookiesToBeAudited should just have 1 element and hence containsAll // check should be ok if (auditTask != null && auditTask.cancel(false)) { auditTask = null; auditorStats.getNumDelayedBookieAuditsCancelled().inc(); } bookiesToBeAudited.clear(); } // find lost bookies(if any) bookiesToBeAudited.addAll(CollectionUtils.subtract(knownBookies, availableBookies)); if (bookiesToBeAudited.size() == 0) { return; } knownBookies.removeAll(bookiesToBeAudited); if (lostBookieRecoveryDelay == 0) { auditorBookieCheckTask.startAudit(false); bookiesToBeAudited.clear(); return; } if (bookiesToBeAudited.size() > 1) { // if more than one bookie is down, start the audit immediately; LOG.info("Multiple bookie failure; not delaying bookie audit. " + "Bookies lost now: {}; All lost bookies: {}", CollectionUtils.subtract(knownBookies, availableBookies), bookiesToBeAudited); if (auditTask != null && auditTask.cancel(false)) { auditTask = null; auditorStats.getNumDelayedBookieAuditsCancelled().inc(); } auditorBookieCheckTask.startAudit(false); bookiesToBeAudited.clear(); return; } if (auditTask == null) { // if there is no scheduled audit, schedule one auditTask = executor.schedule(() -> { auditorBookieCheckTask.startAudit(false); auditTask = null; bookiesToBeAudited.clear(); }, lostBookieRecoveryDelay, TimeUnit.SECONDS); auditorStats.getNumBookieAuditsDelayed().inc(); LOG.info("Delaying bookie audit by {} secs for {}", lostBookieRecoveryDelay, bookiesToBeAudited); } } catch (BKException bke) { LOG.error("Exception getting bookie list", bke); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.error("Interrupted while watching available bookies ", ie); } catch (UnavailableException ue) { LOG.error("Exception while watching available bookies", ue); } }); } synchronized Future<?> submitLostBookieRecoveryDelayChangedEvent() { if (executor.isShutdown()) { SettableFuture<Void> f = SettableFuture.<Void>create(); f.setException(new BKAuditException("Auditor shutting down")); return f; } return executor.submit(() -> { int lostBookieRecoveryDelay = -1; try { waitIfLedgerReplicationDisabled(); lostBookieRecoveryDelay = Auditor.this.ledgerUnderreplicationManager .getLostBookieRecoveryDelay(); // if there is pending auditTask, cancel the task. So that it can be rescheduled // after new lostBookieRecoveryDelay period if (auditTask != null) { LOG.info("lostBookieRecoveryDelay period has been changed so canceling the pending AuditTask"); auditTask.cancel(false); auditorStats.getNumDelayedBookieAuditsCancelled().inc(); } // if lostBookieRecoveryDelay is set to its previous value then consider it as // signal to trigger the Audit immediately. if ((lostBookieRecoveryDelay == 0) || (lostBookieRecoveryDelay == lostBookieRecoveryDelayBeforeChange)) { LOG.info( "lostBookieRecoveryDelay has been set to 0 or reset to its previous value, " + "so starting AuditTask. Current lostBookieRecoveryDelay: {}, " + "previous lostBookieRecoveryDelay: {}", lostBookieRecoveryDelay, lostBookieRecoveryDelayBeforeChange); auditorBookieCheckTask.startAudit(false); auditTask = null; bookiesToBeAudited.clear(); } else if (auditTask != null) { LOG.info("lostBookieRecoveryDelay has been set to {}, so rescheduling AuditTask accordingly", lostBookieRecoveryDelay); auditTask = executor.schedule(() -> { auditorBookieCheckTask.startAudit(false); auditTask = null; bookiesToBeAudited.clear(); }, lostBookieRecoveryDelay, TimeUnit.SECONDS); auditorStats.getNumBookieAuditsDelayed().inc(); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.error("Interrupted while for LedgersReplication to be enabled ", ie); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); } catch (UnavailableException ue) { LOG.error("Exception while reading from ZK", ue); } finally { if (lostBookieRecoveryDelay != -1) { lostBookieRecoveryDelayBeforeChange = lostBookieRecoveryDelay; } } }); } public void start() { LOG.info("I'm starting as Auditor Bookie. ID: {}", bookieIdentifier); // on startup watching available bookie and based on the // available bookies determining the bookie failures. synchronized (this) { if (executor.isShutdown()) { return; } try { watchBookieChanges(); knownBookies = getAvailableBookies(); this.ledgerUnderreplicationManager .notifyLostBookieRecoveryDelayChanged(new LostBookieRecoveryDelayChangedCb()); } catch (BKException bke) { LOG.error("Couldn't get bookie list, so exiting", bke); submitShutdownTask(); return; } catch (UnavailableException ue) { LOG.error("Exception while registering for change notification, so exiting", ue); submitShutdownTask(); return; } scheduleBookieCheckTask(); scheduleCheckAllLedgersTask(); schedulePlacementPolicyCheckTask(); scheduleReplicasCheckTask(); } } protected void submitBookieCheckTask() { executor.submit(auditorBookieCheckTask); } private void scheduleBookieCheckTask() { long bookieCheckInterval = conf.getAuditorPeriodicBookieCheckInterval(); if (bookieCheckInterval == 0) { LOG.info("Auditor periodic bookie checking disabled, running once check now anyhow"); submitBookieCheckTask(); } else { LOG.info("Auditor periodic bookie checking enabled" + " 'auditorPeriodicBookieCheckInterval' {} seconds", bookieCheckInterval); executor.scheduleAtFixedRate(auditorBookieCheckTask, 0, bookieCheckInterval, TimeUnit.SECONDS); } } private void scheduleCheckAllLedgersTask() { long interval = conf.getAuditorPeriodicCheckInterval(); if (interval > 0) { LOG.info("Auditor periodic ledger checking enabled" + " 'auditorPeriodicCheckInterval' {} seconds", interval); long checkAllLedgersLastExecutedCTime; long durationSinceLastExecutionInSecs; long initialDelay; try { checkAllLedgersLastExecutedCTime = ledgerUnderreplicationManager.getCheckAllLedgersCTime(); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); return; } catch (UnavailableException ue) { LOG.error("Got UnavailableException while trying to get checkAllLedgersCTime", ue); checkAllLedgersLastExecutedCTime = -1; } if (checkAllLedgersLastExecutedCTime == -1) { durationSinceLastExecutionInSecs = -1; initialDelay = 0; } else { durationSinceLastExecutionInSecs = (System.currentTimeMillis() - checkAllLedgersLastExecutedCTime) / 1000; if (durationSinceLastExecutionInSecs < 0) { // this can happen if there is no strict time ordering durationSinceLastExecutionInSecs = 0; } initialDelay = durationSinceLastExecutionInSecs > interval ? 0 : (interval - durationSinceLastExecutionInSecs); } LOG.info( "checkAllLedgers scheduling info. checkAllLedgersLastExecutedCTime: {} " + "durationSinceLastExecutionInSecs: {} initialDelay: {} interval: {}", checkAllLedgersLastExecutedCTime, durationSinceLastExecutionInSecs, initialDelay, interval); executor.scheduleAtFixedRate(auditorCheckAllLedgersTask, initialDelay, interval, TimeUnit.SECONDS); } else { LOG.info("Periodic checking disabled"); } } private void schedulePlacementPolicyCheckTask() { long interval = conf.getAuditorPeriodicPlacementPolicyCheckInterval(); if (interval > 0) { LOG.info("Auditor periodic placement policy check enabled" + " 'auditorPeriodicPlacementPolicyCheckInterval' {} seconds", interval); long placementPolicyCheckLastExecutedCTime; long durationSinceLastExecutionInSecs; long initialDelay; try { placementPolicyCheckLastExecutedCTime = ledgerUnderreplicationManager.getPlacementPolicyCheckCTime(); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); return; } catch (UnavailableException ue) { LOG.error("Got UnavailableException while trying to get placementPolicyCheckCTime", ue); placementPolicyCheckLastExecutedCTime = -1; } if (placementPolicyCheckLastExecutedCTime == -1) { durationSinceLastExecutionInSecs = -1; initialDelay = 0; } else { durationSinceLastExecutionInSecs = (System.currentTimeMillis() - placementPolicyCheckLastExecutedCTime) / 1000; if (durationSinceLastExecutionInSecs < 0) { // this can happen if there is no strict time ordering durationSinceLastExecutionInSecs = 0; } initialDelay = durationSinceLastExecutionInSecs > interval ? 0 : (interval - durationSinceLastExecutionInSecs); } LOG.info( "placementPolicyCheck scheduling info. placementPolicyCheckLastExecutedCTime: {} " + "durationSinceLastExecutionInSecs: {} initialDelay: {} interval: {}", placementPolicyCheckLastExecutedCTime, durationSinceLastExecutionInSecs, initialDelay, interval); executor.scheduleAtFixedRate(auditorPlacementPolicyCheckTask, initialDelay, interval, TimeUnit.SECONDS); } else { LOG.info("Periodic placementPolicy check disabled"); } } private void scheduleReplicasCheckTask() { long interval = conf.getAuditorPeriodicReplicasCheckInterval(); if (interval <= 0) { LOG.info("Periodic replicas check disabled"); return; } LOG.info("Auditor periodic replicas check enabled" + " 'auditorReplicasCheckInterval' {} seconds", interval); long replicasCheckLastExecutedCTime; long durationSinceLastExecutionInSecs; long initialDelay; try { replicasCheckLastExecutedCTime = ledgerUnderreplicationManager.getReplicasCheckCTime(); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); return; } catch (UnavailableException ue) { LOG.error("Got UnavailableException while trying to get replicasCheckCTime", ue); replicasCheckLastExecutedCTime = -1; } if (replicasCheckLastExecutedCTime == -1) { durationSinceLastExecutionInSecs = -1; initialDelay = 0; } else { durationSinceLastExecutionInSecs = (System.currentTimeMillis() - replicasCheckLastExecutedCTime) / 1000; if (durationSinceLastExecutionInSecs < 0) { // this can happen if there is no strict time ordering durationSinceLastExecutionInSecs = 0; } initialDelay = durationSinceLastExecutionInSecs > interval ? 0 : (interval - durationSinceLastExecutionInSecs); } LOG.info( "replicasCheck scheduling info. replicasCheckLastExecutedCTime: {} " + "durationSinceLastExecutionInSecs: {} initialDelay: {} interval: {}", replicasCheckLastExecutedCTime, durationSinceLastExecutionInSecs, initialDelay, interval); executor.scheduleAtFixedRate(auditorReplicasCheckTask, initialDelay, interval, TimeUnit.SECONDS); } private class LostBookieRecoveryDelayChangedCb implements GenericCallback<Void> { @Override public void operationComplete(int rc, Void result) { try { Auditor.this.ledgerUnderreplicationManager .notifyLostBookieRecoveryDelayChanged(LostBookieRecoveryDelayChangedCb.this); } catch (ReplicationException.NonRecoverableReplicationException nre) { LOG.error("Non Recoverable Exception while reading from ZK", nre); submitShutdownTask(); } catch (UnavailableException ae) { LOG.error("Exception while registering for a LostBookieRecoveryDelay notification", ae); } Auditor.this.submitLostBookieRecoveryDelayChangedEvent(); } } private void waitIfLedgerReplicationDisabled() throws UnavailableException, InterruptedException { if (!ledgerUnderreplicationManager.isLedgerReplicationEnabled()) { ReplicationEnableCb cb = new ReplicationEnableCb(); LOG.info("LedgerReplication is disabled externally through Zookeeper, " + "since DISABLE_NODE ZNode is created, so waiting untill it is enabled"); ledgerUnderreplicationManager.notifyLedgerReplicationEnabled(cb); cb.await(); } } protected List<String> getAvailableBookies() throws BKException { // Get the available bookies Collection<BookieId> availableBkAddresses = admin.getAvailableBookies(); Collection<BookieId> readOnlyBkAddresses = admin.getReadOnlyBookies(); availableBkAddresses.addAll(readOnlyBkAddresses); List<String> availableBookies = new ArrayList<String>(); for (BookieId addr : availableBkAddresses) { availableBookies.add(addr.toString()); } return availableBookies; } private void watchBookieChanges() throws BKException { admin.watchWritableBookiesChanged(bookies -> submitAuditTask()); admin.watchReadOnlyBookiesChanged(bookies -> submitAuditTask()); } /** * Shutdown the auditor. */ public void shutdown() { LOG.info("Shutting down auditor"); executor.shutdown(); try { while (!executor.awaitTermination(30, TimeUnit.SECONDS)) { LOG.warn("Executor not shutting down, interrupting"); executor.shutdownNow(); } // shutdown all auditorTasks to clean some resource allAuditorTasks.forEach(AuditorTask::shutdown); allAuditorTasks.clear(); if (ownAdmin) { admin.close(); } if (ownBkc) { bkc.close(); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.warn("Interrupted while shutting down auditor bookie", ie); } catch (BKException bke) { LOG.warn("Exception while shutting down auditor bookie", bke); } } @Override public void close() { shutdown(); } /** * Return true if auditor is running otherwise return false. * * @return auditor status */ public boolean isRunning() { return !executor.isShutdown(); } int getLostBookieRecoveryDelayBeforeChange() { return lostBookieRecoveryDelayBeforeChange; } Future<?> getAuditTask() { return auditTask; } }
295
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/package-info.java
/* * 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. */ /** * Classes for replicating Bookkeeper data. */ package org.apache.bookkeeper.replication;
296
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/AuditorTask.java
/** * 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.bookkeeper.replication; import com.google.common.collect.Lists; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.LongAdder; import java.util.function.BiConsumer; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.bookkeeper.net.BookieId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; abstract class AuditorTask implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(AuditorTask.class); protected final ServerConfiguration conf; protected AuditorStats auditorStats; protected BookKeeperAdmin admin; protected LedgerManager ledgerManager; protected LedgerUnderreplicationManager ledgerUnderreplicationManager; private final ShutdownTaskHandler shutdownTaskHandler; private final BiConsumer<AtomicBoolean, Throwable> hasAuditCheckTask; private final AtomicBoolean hasTask = new AtomicBoolean(false); AuditorTask(ServerConfiguration conf, AuditorStats auditorStats, BookKeeperAdmin admin, LedgerManager ledgerManager, LedgerUnderreplicationManager ledgerUnderreplicationManager, ShutdownTaskHandler shutdownTaskHandler, BiConsumer<AtomicBoolean, Throwable> hasAuditCheckTask) { this.conf = conf; this.auditorStats = auditorStats; this.admin = admin; this.ledgerManager = ledgerManager; this.ledgerUnderreplicationManager = ledgerUnderreplicationManager; this.shutdownTaskHandler = shutdownTaskHandler; this.hasAuditCheckTask = hasAuditCheckTask; } @Override public void run() { runTask(); } protected abstract void runTask(); protected boolean isLedgerReplicationEnabled() throws ReplicationException.UnavailableException { return ledgerUnderreplicationManager.isLedgerReplicationEnabled(); } protected CompletableFuture<?> publishSuspectedLedgersAsync(Collection<String> missingBookies, Set<Long> ledgers) { if (null == ledgers || ledgers.size() == 0) { // there is no ledgers available for this bookie and just // ignoring the bookie failures LOG.info("There is no ledgers for the failed bookie: {}", missingBookies); return FutureUtils.Void(); } LOG.info("Following ledgers: {} of bookie: {} are identified as underreplicated", ledgers, missingBookies); auditorStats.getNumUnderReplicatedLedger().registerSuccessfulValue(ledgers.size()); LongAdder underReplicatedSize = new LongAdder(); FutureUtils.processList( Lists.newArrayList(ledgers), ledgerId -> ledgerManager.readLedgerMetadata(ledgerId).whenComplete((metadata, exception) -> { if (exception == null) { underReplicatedSize.add(metadata.getValue().getLength()); } }), null).whenComplete((res, e) -> { auditorStats.getUnderReplicatedLedgerTotalSize().registerSuccessfulValue(underReplicatedSize.longValue()); }); return FutureUtils.processList( Lists.newArrayList(ledgers), ledgerId -> ledgerUnderreplicationManager.markLedgerUnderreplicatedAsync(ledgerId, missingBookies), null ); } protected List<String> getAvailableBookies() throws BKException { // Get the available bookies Collection<BookieId> availableBkAddresses = admin.getAvailableBookies(); Collection<BookieId> readOnlyBkAddresses = admin.getReadOnlyBookies(); availableBkAddresses.addAll(readOnlyBkAddresses); List<String> availableBookies = new ArrayList<String>(); for (BookieId addr : availableBkAddresses) { availableBookies.add(addr.toString()); } return availableBookies; } /** * Get BookKeeper client according to configuration. * @param conf * @return * @throws IOException * @throws InterruptedException */ BookKeeper getBookKeeper(ServerConfiguration conf) throws IOException, InterruptedException { return Auditor.createBookKeeperClient(conf); } /** * Get BookKeeper admin according to bookKeeper client. * @param bookKeeper * @return */ BookKeeperAdmin getBookKeeperAdmin(final BookKeeper bookKeeper) { return new BookKeeperAdmin(bookKeeper, auditorStats.getStatsLogger(), new ClientConfiguration(conf)); } protected void submitShutdownTask() { if (shutdownTaskHandler != null) { shutdownTaskHandler.submitShutdownTask(); } } public abstract void shutdown(); protected boolean hasBookieCheckTask() { hasTask.set(false); hasAuditCheckTask.accept(hasTask, null); return hasTask.get(); } /** * ShutdownTaskHandler used to shutdown auditor executor. */ interface ShutdownTaskHandler { void submitShutdownTask(); } }
297
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/feature/SettableFeatureProvider.java
/* * * 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.bookkeeper.feature; /** * A provider will provide settable features. */ public class SettableFeatureProvider extends CacheableFeatureProvider<SettableFeature> { public static final FeatureProvider DISABLE_ALL = new SettableFeatureProvider("", 0); protected final int availability; public SettableFeatureProvider(String scope, int availability) { super(scope); this.availability = availability; } @Override protected SettableFeature makeFeature(String featureName) { return new SettableFeature(featureName, availability); } @Override protected FeatureProvider makeProvider(String fullScopeName) { return new SettableFeatureProvider(fullScopeName, availability); } }
298
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/feature/FixedValueFeature.java
/* * * 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.bookkeeper.feature; /** * A feature implementation that has a fixed value of availability. */ public class FixedValueFeature implements Feature { protected final String name; protected int availability; public FixedValueFeature(String name, int availability) { this.name = name; this.availability = availability; } public FixedValueFeature(String name, boolean available) { this.name = name; this.availability = available ? FEATURE_AVAILABILITY_MAX_VALUE : 0; } @Override public String name() { return null; } @Override public int availability() { return availability; } @Override public boolean isAvailable() { return availability() > 0; } }
299